一、综述
对于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的用法