shell 命令自动补全模板
示例1
function _xwjh() {
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
# opts="gen init start delete"
opts="gen init start delete"
delete_opts="container config data"
# 添加 init 后的选项
app_opts="account router console"
if [[ ${prev} == "init" ]] ; then
COMPREPLY=( $(compgen -W "${app_opts}" -- ${cur}) )
return 0
elif [[ ${prev} == "delete" ]] ; then
COMPREPLY=( $(compgen -W "${delete_opts}" -- ${cur}) )
return 0
elif [[ ${prev} == "" ]] ; then
COMPREPLY=( $(compgen -W "${delete_opts}" -- ${cur}) )
return 0
elif [[ ${cur} == -* ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
else
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
fi
}
complete -F _xwjh xwjh
示例2
function _custom_completion() {
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
operations=("init" "start" "delete")
objects=("container" "config" "data")
if [[ ${COMP_CWORD} -eq 1 ]]; then
COMPREPLY=( $(compgen -W "${operations[*]}" -- ${cur}) )
return 0
fi
if [[ ${COMP_CWORD} -eq 2 ]]; then
case "${prev}" in
"init")
COMPREPLY=( $(compgen -W "config" -- ${cur}) )
return 0
;;
"start")
COMPREPLY=( $(compgen -W "container" -- ${cur}) )
return 0
;;
"delete")
COMPREPLY=( $(compgen -W "${objects[*]}" -- ${cur}) )
return 0
;;
*)
return 0
;;
esac
fi
if [[ ${COMP_CWORD} -eq 3 ]]; then
case "${prev}" in
"init")
COMPREPLY=( $(compgen -W "config" -- ${cur}) )
return 0
;;
"start")
COMPREPLY=( $(compgen -W "container" -- ${cur}) )
return 0
;;
"delete")
case "${COMP_WORDS[1]}" in
"init")
COMPREPLY=( $(compgen -W "config" -- ${cur}) )
return 0
;;
"start")
COMPREPLY=( $(compgen -W "container" -- ${cur}) )
return 0
;;
"delete")
COMPREPLY=( $(compgen -W "account router console" -- ${cur}) )
return 0
;;
esac
;;
*)
return 0
;;
esac
fi
}
complete -F _custom_completion xwjh