似乎找不到man complete
页面,所以希望人们能够帮助解释完整命令中的选项(来自complete --help
):
complete: complete [-abcdefgjksuv] [-pr] [-DE] [-o option] [-A action] [-G globpat] [-W wordlist] [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] [name ...]
Specify how arguments are to be completed by Readline.
For each NAME, specify how arguments are to be completed. If no options
are supplied, existing completion specifications are printed in a way that
allows them to be reused as input.
Options:
-p print existing completion specifications in a reusable format
-r remove a completion specification for each NAME, or, if no
NAMEs are supplied, all completion specifications
-D apply the completions and actions as the default for commands
without any specific completion defined
-E apply the completions and actions to "empty" commands --
completion attempted on a blank line
When completion is attempted, the actions are applied in the order the
uppercase-letter options are listed above. The -D option takes
precedence over -E.
我试图将bash
脚本的命令作为选项 1 来完成,然后(理想情况下在适当的情况下)使用有效的文件和/或目录。这可以使用complete
还是我需要不同的方法?
现在,我有这个:
complete -W "mount unmount" phone
...对于一个名为 的脚本phone
。
答案1
根据您的要求“帮助解释完整命令中的选项”:
讲述所有细节是一个较长的故事,因此在本文末尾找到希望有用的文档参考列表。
$1
关于作为命令和文件完成的特定用例$2
,我在下一节中添加了一个小示例。
例子
写一个补全函数处理位置差异:
# completion function to differentiate type of completion by argument type
_complete_phone () {
case ${#COMP_WORDS[@]} in
1) # 1st position is the `phone` command itself
return;;
2) # 2nd position are sub-commands, so we use `-W` for word completion
words="mount unmount"
COMPREPLY=($(compgen -W "$words" -- "${COMP_WORDS[COMP_CWORD]}"))
;;
*) # other arguments filter files, either
# any files using option `-f`
#COMPREPLY=($(compgen -f -- "${COMP_WORDS[COMP_CWORD]}"))
# and for specific files (i.e. pattern `*.phone`), use words again
COMPREPLY=($(compgen -W "$(ls *.phone 2>/dev/null)" -- "${COMP_WORDS[COMP_CWORD]}"))
;;
esac
}
然后通过函数激活补全使用参数激活-F
,使用您的完成函数名称:
# complete using your function
complete -F _complete_phone phone
最后,尝试(为了重现性,phone
必须创建任意程序和“相关”文件):
# try
phone () { echo "hello, phone program will $@"; }
touch {my,your}.phone
phone m\tab \tab \tab
文档
Bash 参考手册
当您需要有关bash
.
具体针对 bash 补全,请查看章节
- 8.4可绑定的读取行命令
- 8.4.6 让 Readline 为您打字
- 8.7 可编程完成内置函数
- 8.8 可编程完成示例
来源:www.gnu.org
bash手册
运行man bash
并转到部分:
READLINE
Readline Variables
解释如何处理set
与完成相关的变量。例如set completion-ignore-case on
“以不区分大小写的方式执行文件名匹配和完成”。Completing
默认 bash 完成。Programmable Completion
解释完成的过程,以及在上面的示例中找到的相关元素,例如方法compgen
、变量等。COMP_WORDS
SHELL BUILTIN COMMANDS
compgen
生成完成匹配。complete
来指定如何完成。还描述了所有选项,例如-W
、-F
、-o
等。compopt
设置其他完成选项。
来源:GNU bash,版本 5.1.16(1)-release (x86_64-pc-linux-gnu)