7

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
  • 1,245
  • 1
  • 10
  • 30

3 Answers3

7

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
Keenan
  • 361
  • 3
  • 5
  • 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 ;;` – Ken Feb 21 '22 at 12:26
6

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

Community
  • 1
  • 1
4rk
  • 365
  • 2
  • 15
  • Thanks. Found a possible workaround by including "-:" in the optstring. Wondering what the pitfalls to this approach might be. – kid_x Feb 25 '14 at 21:01
2

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.

kid_x
  • 1,245
  • 1
  • 10
  • 30
  • Pity that this requires the word flags to be prefixed with a double dash. How can I achieve e.g. GCC's `-rdynamic` ? – user2023370 Jun 01 '15 at 21:07