So I have a question about get opts in bash. I want to get the value of the arguments if they are present but if they are not present to use a default value. So the script should take a directory and an integer but if they aren't specified then $PWD and 3 should be default values. Here is what
while getopts "hd:l:" opt; do
case $opt in
d ) directory=$OPTARG;;
l ) depth=$OPTARG;;
h ) usage
exit 0;;
\? ) usage
exit 1;;
esac
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).
optstring must contain the option letters the command using getopts recognizes. If a letter is followed by a colon, the option is expected to have an argument, or group of arguments, which must be separated from it by white space.
You can just provide default value before while
loop:
directory=mydir
depth=123
while getopts "hd:l:" opt; do
case $opt in
d ) directory=$OPTARG;;
l ) depth=$OPTARG;;
h ) usage
exit 0;;
*) usage
exit 1;;
esac
done
echo "<$directory> <$depth>"
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