BASH / CHAPTER 10

Options and positional argument contracts

Intermediate

Parse a command’s interface without losing operands.

By the end of this chapter

  • Use getopts for short options
  • Advance past consumed options
  • Distinguish options from positional data

The idea

getopts parses short options using the shell’s positional parameters and updates OPTIND as it proceeds. An option followed by a colon in the option string requires an argument. After parsing, shifting by OPTIND minus one exposes the remaining operands. A reusable function should manage OPTIND deliberately so previous parsing does not affect a later independent call.

The command interface should define required values, defaults, unknown-option behavior, and whether options may precede operands. A double dash marks the end of option parsing for conventional interfaces, allowing following data to begin with a hyphen. Validate option values after syntactic parsing: recognizing that -n has an argument does not establish that the argument is a supported nonnegative integer or within a safe range.

Bash example
set -- -n 3 alpha
OPTIND=1
limit=1
while getopts ":n:" option; do
 case $option in n) limit=$OPTARG ;; *) exit 2 ;; esac
done
shift "$((OPTIND-1))"
printf '%s:%s\n' "$limit" "$1"
Result
3:alpha

The option value becomes three, and shifting the consumed parameters leaves alpha as the first operand.

Try it yourself

Parse a limit option, reject invalid values, and preserve each remaining filename as an exact argument.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

In a getopts option string, what does n: require?