您好,我正在尝试找到一种方法,使 getopts 能够使用非预期的可选参数
我有一个带有可选参数的脚本
script.sh [-a] [-b] [-c | -d] file
我可以像这样使用 -a..-d
while geopts abc:abd opt
do
case $opt in
a) do this ;;
b) do this ;;
...
..等等
我想让它可以在没有这些参数的情况下工作,这样我就可以像这样运行它
script.sh file
有没有办法制作一个新的案例选项,或者我需要用其他方式来做,谢谢大家的帮助,我是 bash 的初学者。
最佳答案
我以前做过这样的事情:
declare -A have=([a]=false [b]=false [c]=false [d]=false)
while geopts :abcd opt; do
case $opt in
a) have[a]=true ;;
b) have[b]=true ;;
c) have[c]=true ;;
d) have[d]=true ;;
?) echo "illegal option: -$OPTARG"; exit 1;;
esac
done
shift $((OPTIND-1))
if ${have[c]} && ${have[d]}; then
echo "cannot give both -c and -d"
exit 1
fi
${have[a]} && do_a_stuff
${have[b]} && do_b_stuff
...
该 case 语句是相当令人震惊的剪切粘贴编程:加强它:
while geopts :abcd opt; do
case $opt in
a|b|c|d) have[$opt]=true ;;
?) echo "illegal option: -$OPTARG"; exit 1;;
esac
done
关于bash - 没有可选参数的 GETOPTS 情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22596840/