[英]Required option getopts linux
我必须编写一个bash脚本:
schedsim.sh [-h] [-c #CPUs ] -i pathfile
h和c是可选选项。 我是必需的,当运行脚本时,如果它没有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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.