假设我有一个简单的/usr/local/bin/myscript
脚本
#!/bin/bash
case "$1" in
start)
start something
;;
stop)
stop something
;;
status)
status of something
;;
*)
echo "unknown option $1"
esac
我如何以及在何处提供这三个选项开始/停止/状态,以便用户可以按它们显示/自动完成TAB
?
比如apt-get
+2x Tab
给我
autoclean check dselect-upgrade source
autoremove clean install update
build-dep dist-upgrade purge upgrade
changelog download remove
编辑
根据@Ravexina的建议,我添加了一个/etc/bash_completion.d/myscript_comp
文件
_my_script_comp ()
{
local cur # A pointer named "cur" to current completion word.
COMPREPLY=() # Array variable storing the possible completions.
cur=${COMP_WORDS[COMP_CWORD]}
# Show it for every possible combination
# we could do "s*" to only complete words starting with "s"
case "$cur" in
# Generate the completion matches and load them into $COMPREPLY array.
*) COMPREPLY=( $( compgen -W 'start status stop' -- $cur ) );;
esac
return 0
}
complete -F _my_script_comp myscript
但是当我输入myscript
并按下时,2x TAB
我现在会获得当前目录中列出的所有文件,而不是start stop status
......
答案1
在此创建文件:
/etc/bash_completion.d/
随意命名,例如:myscript
。
添加以下行并保存:
_my_script_comp ()
{
local cur # A pointer named "cur" to current completion word.
COMPREPLY=() # Array variable storing the possible completions.
cur=${COMP_WORDS[COMP_CWORD]}
# Show it for every possible combination
# we could do "s*" to only complete words starting with "s"
case "$cur" in
# Generate the completion matches and load them into $COMPREPLY array.
*) COMPREPLY=( $( compgen -W 'start status stop' -- $cur ) );;
esac
return 0
}
complete -F _my_script_comp script.sh
现在您已经获得了 的 bash 补全/usr/local/bin/script.sh
。
我的来源。