Using --getopts to pick up whole word flags

10,132

Solution 1

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.

Solution 2

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

Solution 3

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
Share:
10,132
kid_x
Author by

kid_x

Updated on June 27, 2022

Comments

  • kid_x
    kid_x almost 2 years

    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.

  • kid_x
    kid_x about 10 years
    Thanks. Found a possible workaround by including "-:" in the optstring. Wondering what the pitfalls to this approach might be.
  • user2023370
    user2023370 almost 9 years
    Pity that this requires the word flags to be prefixed with a double dash. How can I achieve e.g. GCC's -rdynamic ?
  • Ken
    Ken about 2 years
    If you want to validate the arguments using something like *) echo "Unknown argument '$1'."; exit 1 ;;, make sure you use shift with the arguments that need a passed value: -a | --aarg) A="$2"; shift ;;
  • Sunlight
    Sunlight almost 2 years
    Using the same code as yours but if I don't pass any arguments to the script inside the while loop $# is always looping between 1 and 2. I can't figure out why this happening :(