多级Bash完成 [英] Multi Level Bash Completion
问题描述
我目前有一个Bash完成文件,该文件从脚本的允许命令列表中完成一个参数(称为"pbt").这是有效的Bash完成文件:
I currently have a Bash completion file which completes a single parameter from a list of allowed commands for a script (called "pbt"). This is the working Bash Completion file:
_pbt_complete()
{
local cur goals
COMPREPLY=()
cur=${COMP_WORDS[COMP_CWORD]}
goals='asadmin clean deploy'
cur=`echo $cur`
COMPREPLY=($(compgen -W "${goals}" ${cur}))
}
complete -F _pbt_complete pbt
所以如果我打电话
pbt <tab>
Bash完成所有允许的命令(asadmin,clean,deploy),这没关系.
Bash completes to all allowed commands (asadmin, clean, deploy), which is okay.
现在,我想为完成添加第二"级别.例如,如果我输入
pbt asadmin <tab>
它应该完成仅在asadmin-环境"(我还将在bash完成文件中定义)内部可用的所有选项,例如pbt asadmin [start-domain|stop-domain]
但如果我键入
it should complete all options that are only available inside the asadmin-"environment" (which i'll also define inside the bash completion file), say for example pbt asadmin [start-domain|stop-domain]
But if i type
pbt deploy <tab>
它应该完成另一组选项,例如pbt deploy [all|current]
.因此,第二个命令的选项应始终取决于第一个命令.我如何在完成文件中做到这一点?
it should complete to another set of options, for example pbt deploy [all|current]
. So the options for the second command should always depend on the first command. How can i do that in the completion file?
推荐答案
Thanks to mkb's comment i looked into the p4-example, which was - unlike the Git example ;) - simple enough for me to adapt it to my case. Here is the working version which does exactly what i asked for:
have pbt &&
_pbt_complete()
{
local cur prev
COMPREPLY=()
cur=${COMP_WORDS[COMP_CWORD]}
prev=${COMP_WORDS[COMP_CWORD-1]}
if [ $COMP_CWORD -eq 1 ]; then
COMPREPLY=( $(compgen -W "asadmin deploy" -- $cur) )
elif [ $COMP_CWORD -eq 2 ]; then
case "$prev" in
"asadmin")
COMPREPLY=( $(compgen -W "start-domain stop-domain" -- $cur) )
;;
"deploy")
COMPREPLY=( $(compgen -W "all current" -- $cur) )
;;
*)
;;
esac
fi
return 0
} &&
complete -F _pbt_complete pbt
这篇关于多级Bash完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!