Bash error: option requires an argument (getopts)
`getopts` reports "option requires an argument" when a flag declared with a colon is passed without a value. Provide the value or change the option spec.
Error String
bash: option requires an argument
Tldr
In `getopts "f:"`, the colon after `f` means "-f takes an argument". Passing `-f` alone triggers this error. Either pass `-f VALUE`, mark the option as flag-only by removing the colon, or use `:` at the start of the option string to opt into silent error handling.
Cause
Mismatch between the option spec and the actual invocation. Frequent in scripts that grew new flags but kept old usage examples.
Repro
while getopts "f:" opt; do
case $opt in
f) file=$OPTARG ;;
esac
done
# ./script.sh -f
# bash: option requires an argument -- fFix
# Silent mode lets you handle missing args yourself:
while getopts ":f:" opt; do
case $opt in
f) file=$OPTARG ;;
:) echo "option -$OPTARG needs a value" >&2; exit 64 ;;
\?) echo "unknown option -$OPTARG" >&2; exit 64 ;;
esac
doneExplanation
The leading colon in the spec switches getopts to silent mode: `:` cases handle missing args, `\?` handles unknown flags. This produces a much better UX than the default error.
Faq
Q
Why does my script work on Linux but not macOS?
A
macOS ships BSD userland; flags such as `sed -i`, `date -d` and `readlink -f` behave differently or do not exist.
Q
What does -- actually do?
A
It marks the end of options, so every following argument is treated as an operand even when it starts with a dash.
Deep Dive
Heading
GNU and BSD tools differ
Body
Most occurrences are portability problems: `sed -i` needs an argument on macOS (`sed -i '' ...`), `date -d` is GNU while BSD wants `date -v`, `readlink -f` is missing on older macOS, and `grep -P` requires PCRE support that is absent on BSD. Either install the GNU versions (`brew install coreutils gnu-sed`, which prefixes them with `g`) or write to the common subset. `command -v gsed >/dev/null && SED=gsed || SED=sed` keeps one script working on both platforms.
Heading
Filenames that look like options
Body
The other cause is a value beginning with a dash reaching the command as a flag — a file called `-report.txt`, or an empty variable followed by user input. Terminate option parsing with `--`: `rm -- "$file"`, `grep -- "$pattern" file`. For paths, `./$file` also works and is clearer in output. Always check the tool's own `--help`, since the invalid-option message comes from the tool rather than from Bash, and the accepted flags vary by version.
Checklist
Confirm which implementation of the tool is on PATH (`command -v`, `--version`).
Add `--` before user-supplied arguments.
Prefix relative paths with `./` when they may begin with a dash.
Use only flags present in both GNU and BSD versions, or detect and branch.