-- signals that there is no more options after it.
It seems to me that when using
-) 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.
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).
#!/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' "$@"
$ 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
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.