BASH: getopts with default parameters value

血红的双手。 提交于 2019-12-02 09:21:35

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"

This works for me:

#!/bin/bash

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

  r)
    fold=/dev
    dir=${2:-$fold}

     echo "asdasd"
  ;;
esac
done

Remove the colon (:) in the getopts argument. This caused getopt to expect an argument. (see here for more information about getopt)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!