
想像一下,我有一個命令“command”,它接受參數foo:bar foo:foo bar:bar 或bar:foo 我可以編寫一個命令列完成腳本,我可以將其來源到我的環境中以提供如下所示的完成:
function _command_opt()
{
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts="foo:bar foo:foo bar:bar bar:foo"
if [[ ${prev: -7} == 'command' ]]
then
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) );
return 0;
fi
}
complete -F _command_opt -o bashdefault -o default 'command'
但是,如果我輸入,command f[tab][tab]
我會列出 foo:bar 和 foo:foo ,但兩者都沒有在我的命令行上完成(因為它們還不清楚。我想要完成的是,這會產生並將command foo:
遊標留在末尾當前單字(而不是添加空格)讓我可以輸入b
或f
然後再次按 Tab 來完成命令。非常有益,例如,25 個不同的命令都以前綴TranslationUpdateprocess: 開頭,而TranslationUpdateProcess 是具有這麼多選項的25 個不同的等長前綴之一。
有誰知道如何讓 bash 完整地以這種方式操作?
答案1
您可以使用以下程式碼(foo:baz foo:qux bar:eat bar:egg
為了清楚起見,我用以下程式碼替換了您的選項):
function _command_opt()
{
local cur cursec command opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
cursec=`echo ${cur} | awk -F ':' '{print $1}'`;
command="${COMP_WORDS[1]}"
opts="foo bar"
case "${command}" in
foo)
COMPREPLY=( $(compgen -W "baz qux" -- ${cursec}) ); return 0;;
bar)
COMPREPLY=( $(compgen -W "eat egg" -- ${cursec}) ); return 0;;
*) ;;
esac
COMPREPLY=( $(compgen -W "${opts}" -S ":" -- ${cur}) ); compopt -o nospace;
}
complete -F _command_opt -o bashdefault -o default 'command'
當您鍵入時,command
tab您可以獲得第一級列表foo: bar:
,當您鍵入時,f
tabtab您可以獲得第二級的完成列表baz qux
。然後,您可以鍵入q
tab以獲取完整的命令行command foo:qux
。
希望能幫助你。