Handling Unknown Options and Invalid Input
Every script that accepts arguments will sooner or later receive ones it cannot use: an option it does not know, an option without its value, a word where a number was expected, two options that contradict each other, or input that contains invisible control characters. How a script reacts decides whether the user fixes the problem in five seconds or gives up. A good reaction stops before doing any work, says exactly what was wrong and where it came from, points to the help, and uses an exit status that other programs can test.
Lessons 127 to 130 already added an "unknown option" branch to each parsing loop, and lesson 128 covered the checks for required arguments and their values. This lesson looks at the whole error path: the kinds of bad input, the difference between usage errors and data errors, suggestions for mistyped options, abbreviations of long options, negative numbers that look like options, reporting several problems at once, displaying hostile input safely, and re-asking when the input comes from a person instead of the command line.
Kinds of Bad Input
It helps to name the cases, because each one needs a slightly different message:
| Problem | Example | Typical message |
|---|---|---|
| Unknown option | -x, --colour | unknown option '-x' |
| Missing option value | -p at the end | option '-p' requires an argument |
| Value for a flag | --verbose=yes | option '--verbose' does not take a value |
| Invalid value | -p 9, -f x | invalid precision '9' (expected 0-6) |
| Missing required option or operand | no -f | missing required option '--from' |
| Conflicting choices | -f c -t c | --from and --to are both 'c' |
| Too many operands | copy.sh a b c | only one SOURCE can be given |
| Bad data while working | a temperature below absolute zero | -5 K is below absolute zero |
All but the last row are usage errors: the command line itself is wrong, and nothing should be done. The last row is a data error: the command line was valid, but one input could not be processed.
Usage Errors Versus Data Errors
The two kinds of error are handled differently:
- A usage error stops the script immediately, before it changes anything. It prints a short message and the
Try '... --help'hint to standard error and exits with status 2, the common convention for wrong usage (lesson 116). Some programs use 64 (EX_USAGEfromsysexits.h) instead; either works as long as the help text says which one the script uses. - A data error affects one item. The script reports it, usually skips that item, continues with the rest, and exits with status 1 at the end, so the caller knows that something failed. There is no point printing the
--helphint here, because the command line was correct.
Keeping the two apart matters to scripts that call yours: status 2 means "fix the command", status 1 means "check the input data".
Stop Before Doing Any Work
A usage error discovered halfway through a job leaves the job half done. Lesson 130 showed a getopts script that had already acted on -v when it found the unknown -x that followed. The reliable structure is:
- The parsing loop only records what the user asked for.
- A validation block checks all values and their combinations.
- Only then does the real work begin.
The complete example at the end of this lesson follows these three steps.
Mistyped Long Options: Suggestions
When a user types --verbsoe instead of --verbose, a plain "unknown option" message makes them search the help. Many modern tools (Git, for example) suggest the closest known option instead. "Closest" is usually measured with the edit distance (Levenshtein distance): the smallest number of single-character insertions, deletions and substitutions that turn one word into the other.
# distance A B: Levenshtein edit distance (insertions, deletions, substitutions)
distance() {
local a=$1 b=$2 i j cost best
local -a prev cur
for (( j = 0; j <= ${#b}; j++ )); do prev[j]=$j; done
for (( i = 1; i <= ${#a}; i++ )); do
cur=("$i")
for (( j = 1; j <= ${#b}; j++ )); do
cost=1
[[ ${a:i-1:1} == "${b:j-1:1}" ]] && cost=0
best=$(( prev[j] + 1 ))
(( cur[j-1] + 1 < best )) && best=$(( cur[j-1] + 1 ))
(( prev[j-1] + cost < best )) && best=$(( prev[j-1] + cost ))
cur[j]=$best
done
prev=("${cur[@]}")
done
echo "${prev[${#b}]}"
}
The function compares the words one character at a time and keeps one row of a table: prev[j] is the distance between the first i - 1 characters of A and the first j characters of B. Each new cell takes the cheapest of three moves: delete a character (prev[j] + 1), insert one (cur[j-1] + 1), or substitute (prev[j-1] + cost, where cost is 0 when the characters already match). The last cell of the last row is the answer:
verbsoe -> verbose: 2
colour -> color: 1
kitten -> sitting: 3
fro -> from: 1
prec -> precision: 5
Swapping two letters (so for os) counts as two substitutions, so verbsoe is at distance 2. The last line shows why edit distance alone is not enough: prec is clearly meant as precision, but it is five letters short. That case is better handled by abbreviations.
A suggestion should be made only when the distance is small (the example uses 2 or less). Otherwise every typo produces a confusing guess. For --colour, no option of the example script is close, so no suggestion is printed.
Unique Abbreviations of Long Options
GNU tools accept any unambiguous prefix of a long option: --prec for --precision, --verb for --verbose. If the prefix matches more than one option, it is an error, and the message lists the candidates. The complete example turns the option name into its full form before the case statement:
long_opts=(from to precision verbose version help)
# expand_long NAME: print the full option name for NAME or a unique prefix of it
expand_long() {
local name=$1 opt d best=99 guess= matches=()
for opt in "${long_opts[@]}"; do
[[ $opt == "$name" ]] && { echo "$opt"; return 0; }
[[ $opt == "$name"* ]] && matches+=("$opt")
done
if (( ${#matches[@]} == 1 )); then echo "${matches[0]}"; return 0; fi
if (( ${#matches[@]} > 1 )); then
fail_usage "option '--$name' is ambiguous; possibilities:$(printf " '--%s'" "${matches[@]}")"
fi
for opt in "${long_opts[@]}"; do
d=$(distance "$name" "$opt")
if (( d < best )); then best=$d guess=$opt; fi
done
if (( best <= 2 )); then
fail_usage "unknown option '--$name'" "did you mean '--$guess'?"
fi
fail_usage "unknown option '--$name'"
}
The order of the checks matters:
- An exact match wins immediately, so an option name that happens to be a prefix of another (
towould be a prefix of a hypotheticaltotal) still works. - Exactly one prefix match is accepted.
- Several prefix matches are an error that names them all.
- No match: the closest option by edit distance is suggested if it is close enough.
$ bash tempconv.sh -f c -t f --verb 20
20 C = 68.0 F
$ bash tempconv.sh -f c -t f --ver 20
tempconv.sh: option '--ver' is ambiguous; possibilities: '--verbose' '--version'
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f c -t f --verbsoe 20
tempconv.sh: unknown option '--verbsoe'
tempconv.sh: did you mean '--verbose'?
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f c -t f --tp f 20
tempconv.sh: unknown option '--tp'
tempconv.sh: did you mean '--to'?
Try 'tempconv.sh --help' for more information.
Abbreviations have one cost: adding a new option later can make an abbreviation that used to work ambiguous. Before --version was added, --ver meant --verbose. Scripts called by other scripts should therefore use full option names.
The caller runs full=$(expand_long "$name") || exit. Because the function runs inside $( ), its exit 2 ends only that subshell (lesson 118); its messages still reach the terminal because they go to standard error, and || exit then ends the script with the same status, 2.
Negative Numbers That Look Like Options
A temperature converter must accept -40. A parsing loop that treats every word starting with - as an option rejects it as an unknown option. There are two solutions, and a good script supports both:
--ends option parsing (lesson 127), sotempconv.sh -f c -t f -- -40always works.- Recognize numbers before options. If the argument matches a negative-number pattern, it is stored as an operand:
if [[ $arg =~ ^-[0-9]+(\.[0-9]+)?$ ]]; then # a negative number, not an option
values+=("$arg"); shift; continue
fi
$ bash tempconv.sh -f c -t f 100 37 -40
212.0
98.6
-40.0
$ bash tempconv.sh -f c -t f -- -40
-40.0
This works because the script has no options whose letters are digits. A script with an option such as -1 cannot use this shortcut, and must rely on --.
Reporting Several Problems at Once
If a command line has three mistakes, a script that stops at the first one makes the user run it three times to find them all. Collecting the messages in an array and reporting them together is friendlier:
errors=()
[[ -n $from ]] || errors+=("missing required option '--from'")
[[ -n $to ]] || errors+=("missing required option '--to'")
[[ $precision =~ ^[0-6]$ ]] || errors+=("invalid precision $(show "$precision") (expected 0-6)")
(( ${#errors[@]} == 0 )) || fail_usage "${errors[@]}"
fail_usage prints each message on its own line, each with the script name in front, and then a single hint:
fail_usage() { # fail_usage MESSAGE...: one line per message, then the hint
local msg
for msg in "$@"; do printf '%s: %s\n' "$prog" "$msg" >&2; done
printf "Try '%s --help' for more information.\n" "$prog" >&2
exit 2
}
$ bash tempconv.sh -f x -t c -p 9 abc 1e3 12.
tempconv.sh: invalid --from unit 'x' (expected c, f or k)
tempconv.sh: invalid precision '9' (expected 0-6)
tempconv.sh: invalid VALUE 'abc' (expected a number such as 21 or -3.5)
tempconv.sh: invalid VALUE '1e3' (expected a number such as 21 or -3.5)
tempconv.sh: invalid VALUE '12.' (expected a number such as 21 or -3.5)
Try 'tempconv.sh --help' for more information.
Writing the loop instead of printf '%s: %s\n' "$prog" "$@" is deliberate: printf reuses its format for the remaining arguments, so it would pair the second message with the third as if it were the program name. Lesson 128 ran into the same effect.
Collecting all errors works only for independent checks. Parsing errors (an unknown option, a missing value) still stop the loop at once, because after them the script can no longer tell which word is an option and which is a value.
Each message also says what was expected. "invalid precision '9'" leaves the user guessing; "(expected 0-6)" tells them how to fix it.
Showing Odd Input Safely
A message that prints the user's input exactly as given can mislead. An argument ending in a newline prints a blank line in the middle of the message; one containing terminal escape sequences can change the colors of the terminal or hide text. A small helper puts normal values in quotes and shows anything with control characters in the $'...' form produced by printf %q:
show() { # quote a value for a message; make control characters visible
if [[ $1 == *[![:print:]]* ]]; then printf '%q' "$1"; else printf "'%s'" "$1"; fi
}
$ bash tempconv.sh -f c -t f $'12\n'
tempconv.sh: invalid VALUE $'12\n' (expected a number such as 21 or -3.5)
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f c -t f $'-\e[31m'
tempconv.sh: unknown option $'-\E[31m'
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f c -t f "1 2"
tempconv.sh: invalid VALUE '1 2' (expected a number such as 21 or -3.5)
Try 'tempconv.sh --help' for more information.
The second argument contains the escape sequence that turns text red. Printed raw, it would have colored the rest of the terminal; through show, it is visible as \E[31m and harmless. [[:print:]] matches printable characters, including the space, so '1 2' is shown in ordinary quotes.
Invalid Input from a Person: Ask Again
Command-line arguments are checked once, and the script exits on error. Input typed at a prompt is different: the person is still there, so the friendly reaction is to explain the problem and ask again, with a limit on the number of attempts. The script must also stop cleanly when input ends (Ctrl + D, or a pipe that runs out), instead of looping forever (lesson 87):
#!/usr/bin/env bash
# ask_number PROMPT MIN MAX: read a whole number in a range, with 3 attempts
ask_number() {
local prompt=$1 min=$2 max=$3 reply tries
for (( tries = 1; tries <= 3; tries++ )); do
printf '%s [%d-%d]: ' "$prompt" "$min" "$max" >&2
if ! IFS= read -r reply && [[ -z $reply ]]; then
printf '\nno answer (end of input)\n' >&2
return 1
fi
if [[ $reply =~ ^[0-9]+$ ]] && (( 10#$reply >= min && 10#$reply <= max )); then
echo "$((10#$reply))"
return 0
fi
printf '%q is not a number from %d to %d\n' "$reply" "$min" "$max" >&2
done
echo "too many invalid answers" >&2
return 1
}
if n=$(ask_number "How many copies" 1 10); then
echo "making $n copies"
else
exit 1
fi
The prompt and the complaints go to standard error, and only the accepted number goes to standard output, so n=$(ask_number ...) captures just the number (lesson 91). 10# makes 07 mean 7 instead of an invalid octal number (lesson 128). The condition ! read && [[ -z $reply ]] accepts a final line without a newline but stops when there is really nothing left.
The runs below used piped input, so the typed answers do not appear after the prompts:
$ printf 'ten\n0\n07\n' | bash ask.sh
How many copies [1-10]: ten is not a number from 1 to 10
How many copies [1-10]: 0 is not a number from 1 to 10
How many copies [1-10]: making 7 copies
$ printf 'x\n\n99\n' | bash ask.sh
How many copies [1-10]: x is not a number from 1 to 10
How many copies [1-10]: '' is not a number from 1 to 10
How many copies [1-10]: 99 is not a number from 1 to 10
too many invalid answers
$ bash ask.sh < /dev/null
How many copies [1-10]:
no answer (end of input)
The last two runs ended with status 1. An empty answer is shown as '', which makes it clear that the person just pressed Enter. Lesson 134 builds whole menus on this kind of loop.
A Complete Example
tempconv.sh converts temperatures. It requires --from and --to, accepts negative values without --, expands abbreviated long options, suggests corrections for typos, reports all validation problems together, and separates usage errors (status 2) from data errors (status 1).
#!/usr/bin/env bash
# tempconv.sh - convert temperatures between Celsius, Fahrenheit and Kelvin
set -euo pipefail
prog=${0##*/}
long_opts=(from to precision verbose version help)
usage() {
cat <<USAGE
Usage: $prog -f UNIT -t UNIT [-p DIGITS] [-v] VALUE...
Convert each VALUE from one temperature unit to another.
UNIT is c (Celsius), f (Fahrenheit) or k (Kelvin).
Options:
-f, --from UNIT unit of the input values (required)
-t, --to UNIT unit of the results (required)
-p, --precision N digits after the decimal point, 0-6 (default: 1)
-v, --verbose print "VALUE UNIT = RESULT UNIT"
-h, --help show this help and exit
--version show version information and exit
Long options may be shortened to any unique prefix (--prec).
Negative values can be given directly: $prog -f c -t f -40
USAGE
}
fail_usage() { # fail_usage MESSAGE...: one line per message, then the hint
local msg
for msg in "$@"; do printf '%s: %s\n' "$prog" "$msg" >&2; done
printf "Try '%s --help' for more information.\n" "$prog" >&2
exit 2
}
show() { # quote a value for a message; make control characters visible
if [[ $1 == *[![:print:]]* ]]; then printf '%q' "$1"; else printf "'%s'" "$1"; fi
}
# distance A B: Levenshtein edit distance (insertions, deletions, substitutions)
distance() {
local a=$1 b=$2 i j cost best
local -a prev cur
for (( j = 0; j <= ${#b}; j++ )); do prev[j]=$j; done
for (( i = 1; i <= ${#a}; i++ )); do
cur=("$i")
for (( j = 1; j <= ${#b}; j++ )); do
cost=1
[[ ${a:i-1:1} == "${b:j-1:1}" ]] && cost=0
best=$(( prev[j] + 1 ))
(( cur[j-1] + 1 < best )) && best=$(( cur[j-1] + 1 ))
(( prev[j-1] + cost < best )) && best=$(( prev[j-1] + cost ))
cur[j]=$best
done
prev=("${cur[@]}")
done
echo "${prev[${#b}]}"
}
# expand_long NAME: print the full option name for NAME or a unique prefix of it
expand_long() {
local name=$1 opt d best=99 guess= matches=()
for opt in "${long_opts[@]}"; do
[[ $opt == "$name" ]] && { echo "$opt"; return 0; }
[[ $opt == "$name"* ]] && matches+=("$opt")
done
if (( ${#matches[@]} == 1 )); then echo "${matches[0]}"; return 0; fi
if (( ${#matches[@]} > 1 )); then
fail_usage "option '--$name' is ambiguous; possibilities:$(printf " '--%s'" "${matches[@]}")"
fi
for opt in "${long_opts[@]}"; do
d=$(distance "$name" "$opt")
if (( d < best )); then best=$d guess=$opt; fi
done
if (( best <= 2 )); then
fail_usage "unknown option '--$name'" "did you mean '--$guess'?"
fi
fail_usage "unknown option '--$name'"
}
from= to= precision=1 verbose=0
values=()
while (( $# > 0 )); do
arg=$1
if [[ $arg =~ ^-[0-9]+(\.[0-9]+)?$ ]]; then # a negative number, not an option
values+=("$arg"); shift; continue
fi
if [[ $arg == --?* ]]; then # --name or --name=value
name=${arg#--}; name=${name%%=*}
full=$(expand_long "$name") || exit
[[ $arg == *=* ]] && arg="--$full=${arg#*=}" || arg="--$full"
fi
case $arg in
-h|--help) usage; exit 0 ;;
-f|--from|-t|--to|-p|--precision)
(( $# > 1 )) || fail_usage "option '$1' requires an argument"
case $arg in
-f|--from) from=$2 ;;
-t|--to) to=$2 ;;
*) precision=$2 ;;
esac
shift ;;
--from=*) from=${arg#*=} ;;
--to=*) to=${arg#*=} ;;
--precision=*) precision=${arg#*=} ;;
-v|--verbose) verbose=1 ;;
--version) echo "$prog 1.0"; exit 0 ;;
--verbose=*|--version=*|--help=*)
fail_usage "option '${arg%%=*}' does not take a value" ;;
--) shift; values+=("$@"); break ;;
-?*) fail_usage "unknown option $(show "$arg")" ;;
*) values+=("$arg") ;;
esac
shift
done
# Check everything and report all problems together.
errors=()
from=${from,,} to=${to,,}
[[ -n $from ]] || errors+=("missing required option '--from'")
[[ -n $to ]] || errors+=("missing required option '--to'")
for u in from to; do
v=${!u}
if [[ -n $v && $v != [cfk] ]]; then
errors+=("invalid --$u unit $(show "$v") (expected c, f or k)")
fi
done
if [[ -n $from && $from == "$to" ]]; then
errors+=("--from and --to are both '$from'; nothing to convert")
fi
[[ $precision =~ ^[0-6]$ ]] || errors+=("invalid precision $(show "$precision") (expected 0-6)")
(( ${#values[@]} > 0 )) || errors+=("no VALUE given")
for v in "${values[@]}"; do
[[ $v =~ ^-?[0-9]+(\.[0-9]+)?$ ]] || errors+=("invalid VALUE $(show "$v") (expected a number such as 21 or -3.5)")
done
(( ${#errors[@]} == 0 )) || fail_usage "${errors[@]}"
# Convert. A value below absolute zero is a data error: report it, go on, exit 1 at the end.
status=0
for v in "${values[@]}"; do
if ! result=$(awk -v v="$v" -v f="$from" -v t="$to" -v p="$precision" 'BEGIN {
c = (f == "c") ? v : (f == "f") ? (v - 32) * 5 / 9 : v - 273.15
if (c < -273.15) exit 3
r = (t == "c") ? c : (t == "f") ? c * 9 / 5 + 32 : c + 273.15
printf "%." p "f\n", r
}'); then
printf '%s: %s %s is below absolute zero\n' "$prog" "$v" "${from^^}" >&2
status=1
continue
fi
if (( verbose )); then
printf '%s %s = %s %s\n' "$v" "${from^^}" "$result" "${to^^}"
else
printf '%s\n' "$result"
fi
done
exit "$status"
How It Works
- Negative numbers are checked first in each pass of the loop, so
-40never reaches the option branches. - Long options are normalized by
expand_longbefore thecasestatement:--prec=2becomes--precision=2and--verbbecomes--verbose. Thecasetherefore needs only the full names. Short options are not abbreviated, so they skip this step. - One branch handles the three options that take a value. It checks that a value exists, and an inner
casestores it in the right variable. --verbose=yesis rejected explicitly. Without that branch it would fall through to-?*and be reported as unknown, which is technically true but less helpful.- Validation runs after parsing and collects every problem, including combinations (
--fromequal to--to). Unit letters are lowercased with${from,,}first, so-f Cis accepted; the indirect expansion${!u}reads the variable whose name is inu(lesson 152 covers it in detail). - The conversion goes through Celsius.
awkconverts the input to Celsius, checks it against absolute zero (-273.15 °C), converts it to the target unit, and prints it with the requested number of decimals. Bash itself has only integer arithmetic (lesson 49). The format string is built from the precision, so"%." p "f\n"becomes"%.2f\n"for-p 2. - A value below absolute zero is a data error.
awkexits with status 3, the script prints a message without the--helphint, skips that value, and exits with 1 after processing the rest.
Running the Complete Example
Normal conversions, including a negative value, the = form, an abbreviation and a separate value for --to:
$ bash tempconv.sh -f c -t f 100 37 -40
212.0
98.6
-40.0
$ bash tempconv.sh -v --from=f --to c 98.6 32
98.6 F = 37.0 C
32 F = 0.0 C
$ bash tempconv.sh --prec 2 -f c -t k -v 21.5
21.5 C = 294.65 K
A data error in the middle of a list. The other values are still converted, and the status is 1:
$ bash tempconv.sh -f k -t c -p 2 0 -5 300
-273.15
tempconv.sh: -5 K is below absolute zero
26.85
Usage errors, each ending with status 2 before any conversion:
$ bash tempconv.sh -f c -t f -x 20
tempconv.sh: unknown option '-x'
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f c -t f --colour 20
tempconv.sh: unknown option '--colour'
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f c -t f --verbose=yes 20
tempconv.sh: option '--verbose' does not take a value
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f C -t c 20
tempconv.sh: --from and --to are both 'c'; nothing to convert
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh 20
tempconv.sh: missing required option '--from'
tempconv.sh: missing required option '--to'
Try 'tempconv.sh --help' for more information.
$ bash tempconv.sh -f c -t f
tempconv.sh: no VALUE given
Try 'tempconv.sh --help' for more information.
The suggestion, ambiguity and odd-input cases were shown in the sections above. Taken together, every message names the script, quotes the offending value in a safe form, says what was expected, and appears before the script has done any work.