我必须编写一个bash脚本:
schedsim.sh [-h] [-c #cpus ] -i pathfile
h和c是可选选项.我是必需的,当运行脚本时,如果它没有i选项 – >错误信息.
另一个问题:如何为选项的参数设置默认值?比方说,如果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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。