![](/img/trans.png)
[英]How to use mutually exclusive flags in your shell and add an optional argument flag ( stuck with getopts)
[英]How to pass in shell scripts mandatory and optional flags in command line using getopts?
我想将3个参数和getopts一起传递给我的shell脚本。 该脚本至少需要前2个,第三个参数是可选的。 如果未设置,则使用其默认值。 因此,以下各项将同时起作用:
sh script.sh -a "/home/dir" -b 3
sh script.sh -a "/home/dir" -b 3 -c "String"
我尝试按照以下方式进行操作,但是它始终忽略我输入的参数。
usage() {
echo "Usage: Script -a <homedir> -b <threads> -c <string>"
echo "options:"
echo "-h show brief help"
1>&2; exit 1;
}
string="bla"
while getopts h?d:t:a: args; do
case $args in
-h|\?)
usage;
exit;;
-a ) homedir=d;;
-b ) threads=${OPTARG};;
-c ) string=${OPTARG}
((string=="bla" || string=="blubb")) || usage;;
: )
echo "Missing option argument for -$OPTARG" >&2; exit 1;;
* )
echo "Unimplemented option: -$OPTARG" >&2; exit 1;;
esac
done
在刚刚按特定顺序添加参数之前,我是这个getopts的新手,我不想在这里做。 我在这里阅读了很多问题,但是一直以来都找不到我需要的方式。
我真的会在这里向您寻求帮助。 谢谢:)
您的脚本中有几个错误。 最重要的是, $args
仅包含选项的字母,没有前划线。 同样,您给getopts( h?d:t:a:
:)提供的选项字符串也不适合您实际处理的选项( h
, ?
, a
, b
, c
)。 这是循环的更正版本:
while getopts "h?c:b:a:" args; do
case $args in
h|\?)
usage;
exit;;
a ) homedir=d;;
b ) threads=${OPTARG};;
c ) string=${OPTARG}
echo "Entered string: $string"
[[ $string=="bla" || $string=="blubb" ]] && usage;;
: )
echo "Missing option argument for -$OPTARG" >&2; exit 1;;
* )
echo "Unimplemented option: -$OPTARG" >&2; exit 1;;
esac
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.