3

By convention -- signals that there is no more options after it. It seems to me that when using getopts with case clause, -) pattern subclause doesn't match --. So what is the behavior of getopts when it meets --? Does it treat -- as an option, a nonoption argument, or neither? Thanks.

10

The behaviour is that it stops parsing the command line and leaves the rest of the arguments as is. The -- itself is removed (or rather $OPTIND will indicate that it was processed but $opt in the code below will never be -, and if you shift "$(( OPTIND - 1 ))" as one usually does, you'll never see it).

Example:

#!/bin/bash

while getopts 'a:b:' opt; do
    case "$opt" in
        a)  printf 'Got a: "%s"\n' "$OPTARG" ;;
        b)  printf 'Got b: "%s"\n' "$OPTARG" ;;
        *)  echo 'error' >&2
            exit 1
    esac
done

shift "$(( OPTIND - 1 ))"

printf 'Other argument: "%s"\n' "$@"

Running it:

$ bash script.sh -a hello -- -b world
Got a: "hello"
Other argument: "-b"
Other argument: "world"

As you can see, the -b world bit of the command line was not processed by getopts.

It stops parsing the command line at -- or at the first non-option argument:

$ bash script.sh something -a hello -- -b world
Other argument: "something"
Other argument: "-a"
Other argument: "hello"
Other argument: "--"
Other argument: "-b"
Other argument: "world"

In this case, -- was not "removed" since getopts never got that far.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.