← 返回博客列表
发布于 2023.01.02 16:54:57 · 约 135 字

shell getopts 关于冒号

while getopts a:b: opt #注释1
# while getopts :a:b: opt #注释2
do
    case $opt in
    a|b)
        echo "选项:[$opt] 值: [$OPTARG]"
        ;;
    :)
        echo "选项 [-$OPTARG] 没有传值"
        exit 1
        ;;
    ?)
        echo "传入了无效选项 [-$OPTARG]"
        exit 2
        ;;
    esac
done

###注释1 冒号跟在字母后面代表要传入参数.

###注释2 最前面的冒号[:]用于指定getopts工作于silent mode,在silent模式下,当用户输入的参数不满足OPTSTRING时,不会将illegal option这样的错误信息打印出来,使代码看起来更加专业。如果想要工作在verbose模式下,可以去掉最前面的冒号。 范例如下:

####上面的例子里, 前面[没有]冒号 while getopts a:b: opt 运行

bash go.sh -a

结果为

go.sh: option requires an argument -- a
传入了无效选项 [-]

####上面的例子里, 前面[有]冒号 while getopts :a:b: opt 运行

bash go.sh -a

结果为

选项 [-a] 没有传值