可选选项参数与getopts的 [英] Optional option argument with getopts

查看:232
本文介绍了可选选项参数与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


  • 级别是指-R的参数,DIR指-d参数

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

      当我输入 ./ count.sh -R 1 -d测试/ 它的工作原理正确

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

      当我输入 ./ count.sh -d测试/ -R 1 它的工作原理正确

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

      但我要使它工作,当我输入 ./ count.sh -d测试/ -R ./计数.SH -R -d测试/

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

      这意味着,我想-R具有默认值和命令的顺序可能会更加灵活。

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

      推荐答案

      getopts的真的不支持这一点;但它并不难写自己更换。

      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
      

      这篇关于可选选项参数与getopts的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆