复杂shell 的参数输入-getopts

一、综述

对于shell 参数的输入有3种

  • 利用 $1 $2,直接将变量给到 $1 $2
      第一个参数会赋值给$1,第二个参数会赋值给$2,以此类推,写简单的shell脚本 可以用
  • getopts
      文章着重讲解,只支持短参数,可以带参数变量,也可以不带参数变量,比如 ./try.sh -f xx1 -v xx2 -m
  • getopt
      可以支持长参数,比如 ./try.sh --prefix=./xxx,这个文章不讲解

二、案例讲解

#!/bin/bash

usage()
{
    echo  "Usage: change_voice_chat_verson.sh [options] para";
    echo  "Replace the test environment version number" 
    echo  "  -f Keyword for conf name."
    echo  "  -v Version to be tested"
    echo  "  "
    echo  "Example: "
    echo  "  \"change_voice_chat_verson.sh -f tongniu_pro -v voice_xxx\"  Name the new configuration file voice_chatbot_voice_xxx.ini and Start the program under the directory voice_xxx."
}

while getopts :f:v: OPTION
do
    case $OPTION in
    f)
        new_conf_keyword=$OPTARG;;
    v)
        new_pro_dir=$OPTARG;;
    h)
        usage;
        exit 0;;
    \?)
        echo "change_voice_chat_verson.sh: invalid option"
        echo "Try \"change_voice_chat_verson.sh -h\" for more infomation."
        exit;;
    esac
done


echo "xxxxx"
echo "new_conf_keyword="$new_conf_keyword
echo "new_conf_keyword="$new_pro_dir

执行结果:

[change_verson]$ ./try.sh -h
change_voice_chat_verson.sh: invalid option
Try “change_voice_chat_verson.sh -h” for more infomation.
[change_verson]$
[change_verson]$ ./try.sh -m
change_voice_chat_verson.sh: invalid option
Try “change_voice_chat_verson.sh -h” for more infomation.
[change_verson]$
[change_verson]$ ./try.sh -f xx1 -v xx2 -m
change_voice_chat_verson.sh: invalid option
Try “change_voice_chat_verson.sh -h” for more infomation.
[change_verson]$
[change_verson]$ ./try.sh -f xx1 -v xx2
xxxxx
new_conf_keyword=xx1
new_conf_keyword=xx2
[change_verson]$

  从代码中,很容易看出,OPTION变量存放的参数标识,具体的变量会存入 OPTARG 中

getopts是bash的内部命令,接受2个参数

  • 第一个参数字符串,字符串的内容是参数标识
    • 最前面的冒号,是表示忽略错误,没有验证,也没遇到这种场景,遇到再说吧
    • 字母后面带冒号,是需要传递参数的,不带冒号是不需要参数的
  • 第二个参数是参数的变量
      看下小例子,很快能明白

参考文章:
[1] getopts的简单用法
[2] shell中case的用法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值