while getopts "hd:R:" arg; do case $arg in h) echo "usage" ;; d) dir=$OPTARG ;; R) if [[ $OPTARG =~ ^[0-9]+$ ]];then level=$OPTARG else level=1 fi ;; \?) echo "WRONG" >&2 ;; esac done
level refers to the parameter of -R
, dir refers to parameters of -d
when I input ./count.sh -R 1 -d test/
it works correctly
when I input ./count.sh -d test/ -R 1
it works correctly
but I want to have it work when I input ./count.sh -d test/ -R
or ./count.sh -R -d test/
This means that I want -R
to have a default value and for the sequence of commands to be more flexible.
Description. The getopts command is a Korn/POSIX Shell built-in command that retrieves options and option-arguments from a list of parameters. An option begins with a + (plus sign) or a - (minus sign) followed by a character. An option that does not begin with either a + or a - ends the OptionString.
The main differences between getopts and getopt are as follows: getopt does not handle empty flag arguments well; getopts does. getopts is included in the Bourne shell and Bash; getopt needs to be installed separately. getopt allows for the parsing of long options ( --help instead of -h ); getopts does not.
On Unix-like operating systems, getopts is a builtin command of the Bash shell. It parses command options and arguments, such as those passed to a shell script. How it works. Specifying the optstring. Verbose error checking.
According to man getopts , OPTIND is the index of the next argument to be processed (starting index is 1).
Wrong. Actually getopts
does support optional arguments! From the bash man page:
If a required argument is not found, and getopts is not silent, a question mark (?) is placed in name, OPTARG is unset, and a diagnostic message is printed. If getopts is silent, then a colon (:) is placed in name and OPTARG is set to the option character found.
When the man page says "silent" it means silent error reporting. To enable it, the first character of optstring needs to be a colon:
while getopts ":hd:R:" arg; do # ...rest of iverson's loop should work as posted done
Since Bash's getopt does not recognize --
to end the options list, it may not work when -R
is the last option, followed by some path argument.
P.S.: Traditionally, getopt.c uses two colons (::
) to specify an optional argument. However, the version used by Bash doesn't.
getopts
doesn't really support this; but it's not hard to write your own replacement.
while true; do case $1 in -R) level=1 shift case $1 in *[!0-9]* | "") ;; *) level=$1; shift ;; esac ;; # ... Other options ... -*) echo "$0: Unrecognized option $1" >&2 exit 2;; *) break ;; esac done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With