getopts in Bash

From the Bash Scripting cheat sheet · Argument Parsing · verified Jul 2026

getopts

Parse single-letter options.

bash
# Quick Reference
while getopts "vo:" opt; do
    case "$opt" in
        v) verbose=1 ;;
        o) out="$OPTARG" ;;
        *) echo "usage..."; exit 1 ;;
    esac
done
💡 In the optstring, a trailing colon (o:) means that option expects an argument in $OPTARG.
⚡ After the loop, shift $((OPTIND-1)) removes options so $@ holds the positional args.
📌 getopts handles only short options (-v); for --long flags, parse with a while/case loop.
🟢 A leading colon in the optstring (":vo:") enables silent error handling you control.
getoptsarguments
Back to the full Bash Scripting cheat sheet