【发布时间】:2017-01-05 16:53:03
【问题描述】:
我想通过 getopts 将 3 个参数传递给我的 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 的新手,在我只是按特定顺序添加参数之前,我不想在这里做。我在这里阅读了很多问题,但不幸的是没有找到我需要的方式。
我真的很想在这里得到您的帮助。谢谢:)
【问题讨论】:
-
您是否查看过 while 循环中
$args的值? getops tutorial 有一些很好的信息;也许你应该先检查那里。
标签: shell command-line-arguments getopts