Can getopts be used to pick up whole-word flags?
Something as follows:
while getopts ":abc --word" opt; do
case ${opt} in
a) SOMETHING
;;
...
--word) echo "Do something else."
;;
esac
done
Trying to pick up those double-dash flags.
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.
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.
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.
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.
Basically Ark's answer but easier and quicker to read than the mywiki page:
#!/bin/bash
# example_args.sh
while [ $# -gt 0 ] ; do
case $1 in
-s | --state) S="$2" ;;
-u | --user) U="$2" ;;
-a | --aarg) A="$2" ;;
-b | --barg) B="$2" ;;
esac
shift
done
echo $S $U, $A $B
#$
is the number of arguments, -gt
is "greater than", $1
is the flag in this case, and $2
is the flag's value.
./example_args.sh --state IAM --user Yeezy -a Do --barg it
results in:
IAM Yeezy, Do it
http://mywiki.wooledge.org/BashFAQ/035 Credit goes to: How can I use long options with the Bash getopts builtin?.
Found one way to do this:
while getopts ":abc-:" opt; do
case ${opt} in
a) echo "Do something"
;;
...
-)
case ${OPTARG} in
"word"*) echo "This works"
;;
esac
esac
done
By adding -: to the opstring and adding a sub-case using $OPTARG, you can pick up the long option you want. If you want to include an argument for that option, you can add * or =* to the case and pick up the argument.
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