getopts 可选参数_Bash - 需要可选参数但不传递以在getopts中使用(Bash - optional argument required but not passed for use ...

这篇博客详细介绍了如何在Shell脚本中处理错误和解析命令行选项。通过使用`getopts`函数,可以自定义错误处理,并检查选项是否缺少值。文章提到了特定的错误情况,如未提供选项值时的错误处理,以及如何避免类似`-h`被误解析为`-t`的OPTARG。所有错误消息都定向到标准错误输出,并通过`exit`命令配合不同退出状态码来结束脚本执行。
摘要由CSDN通过智能技术生成

Several points here:

# Note the leading ':'

while getopts :ht: OPTION

do

case $OPTION in

h)

echo "Hi"

;;

t)

echo "You entered $OPTARG"

if [[ ${OPTARG:0:1} == '-' ]]; then

echo "Invalid value $OPTARG given to -$OPTION" >&2

exit 1

fi

;;

:) echo "$0: -$OPTARG needs a value" >&2;

exit 2

;;

\?) echo "$0: unknown option -$OPTARG" >&2;

exit 3

;;

esac

done

The leading ':' on the option list allows us to do our own error handling. If an unknown option is supplied then OPTION is set to a ?. Note that in the case statement this has to be escaped (prefixed with a \), otherwise it would match any single character.

If a value is not supplied to an option, then OPTION is set to a :. Unfortunately this does not help if someone does:

./x -t -h

since the -h will be taken as the OPTARG to option -t. Hence the extra test.

Notice that all the error messages go to standard-error (>&2). To halt the execution of the script we use exit followed by a number in the range 0-255. The only number with a specific meaning is zero, which means success. The numbers 1-255 can have any meaning that we choose, but all imply failure.

Using your examples:

./x.sh -t -h

You entered -h

Invalid value -h given to -t

./x.sh -h -t aa

Hi

You entered aa

./x.sh -h -t

Hi

./x.sh: -t needs a value

./x.sh -t tea -c

You entered tea

./x.sh: unknown option -c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值