bash completion模板

前景

常见指令格式: 一个横线-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
  • 第一种: 参数补全;

  • 第二种: 选项补全;

  • 第三种; 同样的选项补全; 甚至二三可以合并;

  • 第四种; 参数补全; 如果没有参数, 建议使用第二三种的任意一种规则, 但是需要拆分;

案例解析

bashcompletion机制会按照COMP_WORDBREAKS记录的值进行分词;

通过_get_comp_words_by_ref函数将参数进行二次处理;

${cur} ${prev}的值和${COMP_WORDS[COMP_CWORD]} ${COMP_WORDS[COMP_CWORD - 1]}的值是不一样的;

总结: 补全的返回值会用于替换当前的${COMP_WORDS[COMP_CWORD]}, 和上面的cur,prev值需要区分;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值