问题描述
我是 compgen
的新手,想将它用于我正在处理的脚本。此脚本可以将“命令”和“选项”作为参数,如下所示:
script add "value"
script --path "/a/file/path" add "value"
# and others
我写了一个看起来像这样的完成脚本:
_script_completions() {
arg_index="${COMP_CWORD}"
if [[ "${arg_index}" -eq 1 ]]; then
COMPREPLY=($(compgen -W "--path add" "${COMP_WORDS[1]}"))
fi
}
complete -F _script_completions script
此脚本对于“add”命令运行良好,但在“--path”选项上失败。例如: 当我输入:
$ script --p<TAB>
我明白了:
$ ./script --pbash: compgen: --: invalid option
compgen: usage: compgen [-abcdefgjksuv] [-o option] [-A action] [-G globpat] [-W wordlist] [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] [word]
如何正确为自己的脚本选项添加补全?
解决方法
使用 compgen -W "--path add" "${COMP_WORDS[1]}"
和 script --p<tab>
,最后一个参数 ${COMP_WORDS[1]}
变成 --p
,然后被解释为 compgen
的选项,而不是要完成的单词。您可以使用参数 --
来标记选项的结束:
_script_completions() {
arg_index="${COMP_CWORD}"
if [[ "${arg_index}" -eq 1 ]]; then
COMPREPLY=($(compgen -W "--path add" -- "${COMP_WORDS[1]}"))
fi
}
complete -F _script_completions script