Linux Basic — getopts Option Parsing
getopts Option Parsing
getopts is the portable way to parse short options (-a -b -f arg) in POSIX-style shells. It is not getopt (which is less portable and complex).
Basic Pattern
usage() { echo "Usage: $0 [-a] [-b arg]"; exit 1 }
while getopts ":ab:" opt; do
case $opt in
a) flag_a=1 ;;
b) arg_b=$OPTARG ;;
:) echo "Option -$OPTARG requires an argument."; usage ;;
\?) echo "Invalid option: -$OPTARG"; usage ;;
esac
done
shift $((OPTIND -1)) # remaining args
-
:ab:— options string:ano arg,b:requires an arg - Leading
:switchesgetoptsinto silent (POSIX) error reporting mode -
$OPTARGholds the option argument
Boolean Flags
Combine multiple flags easily:
while getopts "abc" opt; do
case $opt in
a) a=1;;
b) b=1;;
c) c=1;;
esac
done
Long Options (Not getopts) — Use a Simple Workaround
getopts doesn’t handle --long natively. For mixed short/long, parse -- manually first:
while [[ "$1" == --* ]]; do
case "$1" in
--help) usage;;
--version) echo "v1"; exit 0;;
esac
shift
done
# then fallback to getopts for short options
For full long-option parsing prefer argbash, getopt with caution, or a small parser.
Idiomatic Usage Message
- Keep
usage()short and practical - Print default values and examples
- Use
$0in help so the message works when the script is renamed
Next → yes/no Confirmation