Optional option argument with getopts

前端 未结 11 1300
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:09

    I think there are two way.

    First is calandoa's answer, Using OPTIND and no silent mode.

    Second is Using OPTIND and silent mode.

    while getopts ":Rr:" name; do
        case ${name} in
            R)
                eval nextArg=\${$OPTIND}
                # check option followed by nothing or other option.
                if [[ -z ${nextArg} || $nextArg =~ ^-.* ]]; then
                    level=1
                elif [[ $nextArg =~ ^[0-9]+$ ]]; then
                    level=$nextArg
                    OPTIND=$((OPTIND + 1))
                else
                    level=1
                fi
                ;;
            r)
                # check option followed by other option.
                if [[ $OPTARG =~ ^-.* ]]; then
                    OPTIND=$((OPTIND - 1))
                    level2=2
                elif [[ $OPTARG =~ ^[0-9]+$ ]]; then
                    level2="$OPTARG"
                else
                    level2=2
                fi
                ;;
            :)
                # check no argument
                case $OPTARG in
                    r)
                        level2=2
                        ;;
                esac
        esac
    done
    
    echo "Level 1 : $level"
    echo "Level 2 : $level2"
    

提交回复
热议问题