Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using --getopts to pick up whole word flags

Tags:

bash

unix

getopts

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.

like image 730
kid_x Avatar asked Feb 25 '14 20:02

kid_x


People also ask

Should I use getopt or getopts?

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.

What is the purpose of getopts command?

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.

What does getopts do in Bash?

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.

What does colon mean in getopts?

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.


3 Answers

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
like image 185
Keenan Avatar answered Nov 15 '22 07:11

Keenan


http://mywiki.wooledge.org/BashFAQ/035 Credit goes to: How can I use long options with the Bash getopts builtin?.

like image 35
4rk Avatar answered Nov 15 '22 06:11

4rk


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.

like image 20
kid_x Avatar answered Nov 15 '22 08:11

kid_x