前景
常见指令格式: 一个横线
-all
; 横线带参数-type t1
; 两个横线; 两个横线带参数; 指令参数;
详细:command [-all] [-type type_value] [--all] [--type value] [arugments]
简写:command [option] [arguments]
模板
四种参数; 四种处理
source /etc/bash_completion function _xlunch { local cur prev double_opts double_vals single_opts single_vals _get_comp_words_by_ref -n = cur prev echo "pre:${prev};cur:${cur}" >> log.txt # double opts, double opts with value; single opts; single opt with value; double_opts="help all mtk qcom samsung krin" double_vals="product type" single_opts="h p t m q s k a" # transform "-t t1" to "-t=t1" declare -A single_vals single_vals=([-t]=1 [-p]=1) if [[ "${prev}" == -[^-]* && ${single_vals[${prev}]} ]]; then cur="${prev}=${cur}" fi # start to process, and return completion set; case ${cur} in ########################## option with arg ###################################### # --name=value --product=* | -p=*) COMPREPLY=($(compgen -W "p1 p2" ${cur#*=})) ;; --type=* | -t=*) COMPREPLY=($(compgen -W "t1 t2" ${cur#*=})) ;; ########################## -- options ###################################### --*) COMPREPLY=($(compgen -W "${double_opts}" -P "--" ${cur#--})) COMPREPLY+=($(compgen -W "${double_vals}" -P "--" -S "=" ${cur#--})) if [[ ${#COMPREPLY[@]} -eq 1 && "${COMPREPLY[0]}" == *= ]]; then compopt -o nospace; fi ;; ########################## - options ###################################### -*) COMPREPLY=($(compgen -W "${single_opts}" -P "-" ${cur#-})) ;; ########################## arguments ###################################### *) COMPREPLY=($(compgen -W "target1 target2" ${cur})) ;; esac # add space when you tab at middle of command if [[ ${#COMPREPLY[@]} -eq 1 && "${COMPREPLY[0]}" != *= && ${#COMP_WORDS[@]} -ne 1+${COMP_CWORD} ]]; then COMPREPLY[0]+=" "; fi } && complete -F _xlunch xlunch
案例解析
bash
的completion
机制会按照COMP_WORDBREAKS
记录的值进行分词;通过
_get_comp_words_by_ref
函数将参数进行二次处理;
${cur} ${prev}
的值和${COMP_WORDS[COMP_CWORD]} ${COMP_WORDS[COMP_CWORD - 1]}
的值是不一样的;