Search code examples
bashunixgetopts

Using --getopts to pick up whole word flags


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.


Solution

  • 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.