Optional option argument with getopts

前端 未结 11 1295
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 08:56

    I just ran into this myself and felt that none of the existing solutions were really clean. After working on it a bit and trying various things, I found that leveraging getopts SILENT mode with :) ... appears to have done the trick along with keeping OPTIND in sync.


    usage: test.sh [-abst] [-r [DEPTH]] filename
    *NOTE: -r (recursive) with no depth given means full recursion
    
    #!/usr/bin/env bash
    
    depth='-d 1'
    
    while getopts ':abr:st' opt; do
        case "${opt}" in
            a) echo a;;
            b) echo b;;
            r) if [[ "${OPTARG}" =~ ^[0-9]+$ ]]; then
                   depth="-d ${OPTARG}"
               else
                   depth=
                   (( OPTIND-- ))
               fi
               ;;
            s) echo s;;
            t) echo t;;
            :) [[ "${OPTARG}" = 'r' ]] && depth=;;
            *) echo >&2 "Invalid option: ${opt}"; exit 1;;
        esac
    done
    shift $(( OPTIND - 1 ))
    
    filename="$1"
    ...
    

提交回复
热议问题