【发布时间】:2019-03-04 13:28:33
【问题描述】:
我的问题是,当我使用脚本下面的 sn-ps 时,当我没有为选项提供参数时,会阻塞命令。如果我确实包含参数,一切都很好,我可以按任何顺序输入选项。
如何确保使用 getopts 将不同的选项(-s 和 -f)正确映射到它们的变量?
请看下面的例子。
./script.bash -ftestfile -s0
search flag: 0
file: testfile
./script.bash -s0 -ftestfile
search flag: 0
file: testfile
到目前为止一切顺利..
当 f 选项不带参数(示例中的 testfile)时,问题就会出现。似乎 getopts 不再能够识别 -s 应该是 inputsearch 而 -f 仍然是 inputfile。
./script.bash -f -s0
search flag:
file: -s0
这里的魔法
s=0
while getopts :s:f:ih option
do
case "${option}" in
s) inputsearch=${OPTARG};;
f) inputfile=${OPTARG};;
h) display_help; exit 1;;
?) display_help; exit 1;;
esac
done
# crap validation (must contain some option and option cant simply be "-" or "--"
if [ -z "$1" ] || [ "$1" = "-" ] || [ "$1" = "--" ]
then
display_help
exit 1
fi
#this fails
if [[ $inputsearch -gt 1 ]] || [[ -z $inputfile ]]
then
display_help
exit 1
else
echo "search flag: $inputsearch"
echo "file: $inputfile"
fi
感谢您的意见!
【问题讨论】:
-
getopts根本不支持选项的可选参数。-f之后的下一个参数将作为其参数,无论它是否也匹配另一个选项。
标签: bash command-line-arguments getopts