getopts 可选参数_可选选项参数与getopts的

while getopts "hd:R:" arg; do

case $arg in

h)

echo "usgae"

;;

d)

dir=$OPTARG

;;

R)

if [[ $OPTARG =~ ^[0-9]+$ ]];then

level=$OPTARG

else

level=1

fi

;;

\?)

echo "WRONG" >&2

;;

esac

done

level refers to parameter of -R, dir refers to parameters of -d

when I input ./count.sh -R 1 -d test/ it works rightly

when I input ./count.sh -d test/ -R 1 it works rightly

but I want to make it work when I input ./count.sh -d test/ -R or ./count.sh -R -d test/

This means that I want -R has a default value and the sequence of command could be more flexible.

解决方案

getopts doesn't really support this; but it's not hard to write your own replacement.

while true; do

case $1 in

-R) level=1

shift

case $1 in

*[!0-9]* | "") ;;

*) level=$1; shift ;;

esac ;;

# ... Other options ...

-*) echo "$0: Unrecognized option $1" >&2

exit 2;;

*) break ;;

esac

done

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值