Bash getopts意外地解析脚本参数



我有以下bash脚本:

#!/bin/bash
function usage() {
printf "n"
echo "Updates a Lambda with env vars stored in a Secrets Manager secret. Complete drop n' swap."
printf "n"
echo "Syntax: bash $0 -a <ARN> -s <secretName> [-h]"
echo "options:"
echo "a       the ARN of the Lambda to update"
echo "s       the name of the secret in Secrets Manager to use"
echo "h       display help"
printf "n"
exit
}
while getopts ":has:" option; do
case $option in
h) # display help
usage
;;
a) # ARN of the lambda
arn=${OPTARG}
[[ -z "$arn" ]] && usage
;;
s) # Secrets Manager secret (name)
secretName=${OPTARG}
[[ -z "$secretName" ]] && usage
;;
*) # catchall
usage
esac
done
echo "all good! arn = $arn and secret = $secretName"

当我运行这个时,我得到:

myuser@mymachine myapp % bash myscript.sh -a abba -s babba
Updates a Lambda with env vars stored in a Secrets Manager secret. Complete drop n' swap.
Syntax: bash myscript.sh -a <ARN> -s <secretName> [-h]
options:
a       the ARN of the Lambda to update
s       the name of the secret in Secrets Manager to use
h       display help

我希望所有的参数(由getopts解析(都是有效的,并看到"all good!..."的输出而不是用法输出。

我哪里出岔子了?我是错误地使用/解析了getopts,还是错误地调用了带有参数的脚本?还是两者都有?!提前感谢!

由于-a应该有一个关联的值,因此您希望将:附加到a选项,即:

# change this:
while getopts ":has:" option
# to this:
while getopts ":ha:s:" option
^--------------

最新更新