The option string
The getopts builtin parses the arguments of a script according to an option string. Each letter in the string is a flag that the script accepts. A letter followed by a colon takes a value. The string vn: means the script accepts -v as a flag and -n with a value. Option names are single characters, so long options such as --verbose are outside what getopts handles.
The getopts command is a shell builtin, so it is available in every bash script without installing anything. The separate getopt program from util-linux can handle long options, but it is not portable, and scripts that need only short options usually choose getopts. The getopt(3) manual page describes the C function that these conventions come from.
A loop with getopts
The usual pattern is a while loop around getopts, with a case statement on the option letter. The getopts command stores the current letter in the variable you name. It returns status 0 while options remain, and status 1 when it runs out of them.
verbose=0
while getopts "vn:" opt; do
case $opt in
v) verbose=1 ;;
n) name=$OPTARG ;;
esac
doneSet the defaults before the loop, so that options the caller leaves out keep their values. Each letter in the case must match the option string exactly. A flag sets a variable, and a value option copies the value from OPTARG into a variable. Quoting the option string is a good habit, even though it contains no characters that the shell would expand.
Values, OPTARG and OPTIND
For an option that takes a value, getopts stores the value in OPTARG. Both -n ana and -nana work, because getopts accepts the value attached to the letter as well as the value in the next word. The variable OPTIND holds the index of the next argument to process. It starts at 1 and advances as options are consumed.
Every option that takes a value must consume it, and getopts does that for you. The value after -n is never mistaken for a file name, even when it looks like an option. For instance, -n -v stores the text -v as the name, because the colon in the option string tells getopts that the next word belongs to -n. A script that wants to reject values that start with a hyphen has to check OPTARG itself after the loop.
Bundled flags work too. The input -vn ana is read as -v followed by -n with the value ana. This is the same convention that tar and ls follow. Each letter in a bundle is a separate option, and the loop visits them in order.
Removing the options
When the loop ends, the options are still among the positional parameters. Remove them with shift $((OPTIND - 1)), which drops everything getopts consumed. After that, $1 is the first file name or other plain argument, and $# counts only those. The value of OPTIND tells you how many words to skip, which is why the line is written this way.
shift $((OPTIND - 1))
for file in "$@"; do
echo "$file"
doneErrors and the leading colon
An unknown option makes getopts set opt to a question mark, and it stores the offending letter in OPTARG. A missing value makes opt a colon, with the option letter in OPTARG. By default bash also prints its own message to standard error. A case branch for the question mark and the colon lets you print your usage text and exit with status 2 instead.
If the option string starts with a colon, as in :vn:, getopts runs in silent mode. It stops printing its own messages, and it reports a missing value with the colon. Silent mode gives the script full control of the message, which is the reason to choose it for tools that have a fixed usage format.
The end of options
A double dash, --, ends the options explicitly. Anything after it is a plain argument, even if it starts with a hyphen. This is how you pass a file named -notes to a script. The getopts command stops at the double dash and consumes it, so the shift removes it too.
Designing the flags of a tool
Choosing which options to add is a design decision, and getopts makes the mechanics easy. Keep flags for choices that are on or off, such as verbose output. Use a value option when the caller must supply information, such as a name or a path. Give every option a single letter that matches the first letter of its meaning, when you can, so that the script is easy to remember. Document the options in the usage line, because the usage line is the first thing a user reads when a call goes wrong.
Defaults belong before the loop, and they should be the safest values. A verbose flag that defaults to off keeps normal output quiet. A name that defaults to a neutral value is easier to test than one that reads the current user. When a default could cause harm, such as deleting files, make the caller ask for it explicitly.
Order of options is not important to getopts. The script sees -v -n ana and -n ana -v as the same request, and it can treat the remaining words as its input in either case. This flexibility is one reason getopts is preferred over reading $1 directly, which would force a fixed order on callers.
Hands-on: a small greeter
The block below shows the pattern on a small scale, with a usage branch for unknown options. Use it as a starting point rather than a finished tool.
cat > greet.sh << 'EOF'
verbose=0
name=anon
while getopts "vn:" opt; do
case $opt in
v) verbose=1 ;;
n) name=$OPTARG ;;
*) echo "usage: greet.sh [-v] [-n NAME]" >&2; exit 2 ;;
esac
done
shift $((OPTIND - 1))
echo "verbose=$verbose name=$name"
EOF
bash greet.sh -v -n ana
bash greet.sh -vnana
bash greet.sh -xThe first two calls print the same line, because -vnana is the bundled form of -v -n ana. The last call prints the usage line and exits with status 2, which is the convention for misuse of a command.