Shell自动补全传参简单demo

准备两个文件:

File1: env.bash

_buildsh_prompt()
{
    COMPREPLY=()
    local cur=${COMP_WORDS[COMP_CWORD]};
    local cmd=${COMP_WORDS[COMP_CWORD-1]};

    local opts=(-a -b -c all clean)
    local a_opts=(a_1 a_2 a_3)
    local b_opts=(b_1 b_2 b_3)
    local c_opts=(C1 C2 C3 C4)
    local module_opts=(all all_32 clean)
    local path=$(pwd)
    local SRC_BUILD_DIR=$(pwd)

    case $cmd in
        -a)
            COMPREPLY=( $(compgen -W '${a_opts[@]}' -- $cur) )
            ;;
        -b)
            COMPREPLY=( $(compgen -W '${b_opts[@]}' -- $cur) )
            ;;
        -c)
            COMPREPLY=( $(compgen -W '${c_opts[@]}' -- $cur) )
            ;;
        *)
            COMPREPLY=( $(compgen -W '${opts[@]}' -- $cur) )
            ;;
        esac

}

complete -F _buildsh_prompt build_test.sh

File2: build_test.sh


while getopts "a:b:c:" opt
do
    case $opt in
        a)
            if [ "$OPTARG" = "a_1" ];then
                echo "get in a_1 function"
            elif [ "$OPTARG" = "a_2" ];then
                echo "get in a_2 function"
            elif [ "$OPTARG" = "a_3" ];then
                echo "get in a_3 function"
            else
                echo "Error: Invalid -c $OPTARG"
                exit 1
            fi
            ;;
        b)
            if [ "$OPTARG" = "b_1" ];then
                echo "get in b_1 function"
            elif [ "$OPTARG" = "b_2" ];then
                echo "get in b_2 function"
            elif [ "$OPTARG" = "b_3" ];then
                echo "get in b_3 function"
            else
                echo "Error: Invalid -b $OPTARG"
                exit 1
            fi
            ;;
        c)
            if [ "$OPTARG" = "C1" ];then
                echo "get in C1 function"
            elif [ "$OPTARG" = "C2" ];then
                echo "get in C2 function"
            elif [ "$OPTARG" = "C3" ];then
                echo "get in C3 function"
            else
                echo "Error: Invalid -b $OPTARG"
                exit 1
            fi
            ;;
        \?)
            exit 1
            ;;
    esac
done

开始测试

  • source env.bash
  • ./build_test.sh [tab]
  • ./build_test.sh -a [tab]

结果

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值