BASH: getopts with default parameters value

前端 未结 2 1401
有刺的猬
有刺的猬 2021-01-27 18:47

I\'ve got another bash-script problem I simply couldn\'t solve. It\'s my simplified script showing the problem:

while getopts \"r:\" opt; do
case $opt in

  r)
          


        
2条回答
  •  无人共我
    2021-01-27 19:17

    There may be other parameters before, don't hard-code the parameter number ($2).

    The getopts help says

    When an option requires an argument, getopts places that argument into the shell variable OPTARG.
    ...
    [In silent error reporting mode,] if a required argument is not found, getopts places a ':' into NAME and sets OPTARG to the option character found.

    So you want:

    dir=/dev                            # the default value
    while getopts ":r:" opt; do         # note the leading colon
        case $opt in
            r) dir=${OPTARG} ;;
            :) if [[ $OPTARG == "r" ]]; then
                   # -r with required argument missing.
                   # we already have a default "dir" value, so ignore this error
                   :
               fi
               ;;
        esac
    done
    shift $((OPTIND-1))
    
    a=$(find "$dir" -type b | wc -l)
    echo "$a"
    

提交回复
热议问题