【发布时间】:2014-10-11 16:11:41
【问题描述】:
我必须写一个 bash 脚本:
schedsim.sh [-h] [-c #CPUs ] -i pathfile
h 和 c 是可选选项。 i 是必需的,如果没有 i 选项,则在运行脚本时 -> 错误消息。
如何在 getopts 中设置一个必需的选项? 谢谢!
另一个问题:如何为选项的参数设置默认值?比如说,如果 c 没有提供参数 -> c 的参数的默认值为 1。
【问题讨论】:
我必须写一个 bash 脚本:
schedsim.sh [-h] [-c #CPUs ] -i pathfile
h 和 c 是可选选项。 i 是必需的,如果没有 i 选项,则在运行脚本时 -> 错误消息。
如何在 getopts 中设置一个必需的选项? 谢谢!
另一个问题:如何为选项的参数设置默认值?比如说,如果 c 没有提供参数 -> c 的参数的默认值为 1。
【问题讨论】:
您不能像“如果缺少该参数,则内置 getopts 将返回错误”中那样使参数成为必需。
但是自己做一个函数是微不足道的:
#!/bin/bash
function parseArguments () {
local b_hasA=0
local b_hasB=0
local b_hasC=0
while getopts 'a:b::c' opt "$@"; do
case $opt in
'a')
b_hasA=1
;;
'b')
b_hasB=1
;;
'c')
b_hasC=1
;;
esac
done
if [ $b_hasA -ne 0 ]; then
echo "A present"
fi
if [ $b_hasB -ne 0 ]; then
echo "B present"
fi
if [ $b_hasC -ne 0 ]; then
echo "C present"
else
echo "Error: C absent"
exit 1
fi
}
#Quotes required to avoid removing characters in $IFS from arguments
parseArguments "$@"
测试:
$ ./test.bash -c
C present
$ ./test.bash -b
./test.bash: option requires an argument -- b
Error: C absent
$ ./test.bash -b foo
B present
Error: C absent
【讨论】: