Optional option argument with getopts

前端 未结 11 1313
while getopts \"hd:R:\" arg; do
  case $arg in
    h)
      echo \"usgae\" 
      ;;
    d)
      dir=$OPTARG
      ;;
    R)
      if [[ $OPTARG =~ ^[0-9]+$ ]];then         


        
11条回答
  •  野性不改
    2020-11-28 09:12

    This is actually pretty easy. Just drop the trailing colon after the R and use OPTIND

    while getopts "hRd:" opt; do
       case $opt in
          h) echo -e $USAGE && exit
          ;;
          d) DIR="$OPTARG"
          ;;
          R)       
            if [[ ${@:$OPTIND} =~ ^[0-9]+$ ]];then
              LEVEL=${@:$OPTIND}
              OPTIND=$((OPTIND+1))
            else
              LEVEL=1
            fi
          ;;
          \?) echo "Invalid option -$OPTARG" >&2
          ;;
       esac
    done
    echo $LEVEL $DIR
    

    count.sh -d test

    test

    count.sh -d test -R

    1 test

    count.sh -R -d test

    1 test

    count.sh -d test -R 2

    2 test

    count.sh -R 2 -d test

    2 test

提交回复
热议问题