Arguments, Usage and Exit Codes
A script's command line is its API. CI jobs, cron entries and colleagues will call it in ways you did not plan, and
they will rely on its exit status. Script Arguments in the Linux course covers $1, $@ and
shift; this lesson builds an interface that behaves like the standard tools: short and long options, --,
defaults from the environment, a help text, and meaningful exit codes.
Long and short options with a while/case loop
getopts (shown in Anatomy of a Production Script) only knows single-letter
options. Most DevOps tools also take --long options, and a plain while/case loop handles both with no external
dependency:
cat > rotate <<'SCRIPT'
#!/usr/bin/env bash
# rotate: delete old files from a directory
set -euo pipefail
PROG=${0##*/}
usage() {
cat <<EOF
Usage: $PROG [options] DIR
-k, --keep N keep the newest N files (default: \$ROTATE_KEEP or 5)
-n, --dry-run show what would be deleted
-h, --help show this help
EOF
}
die_usage() { echo "$PROG: $*" >&2; usage >&2; exit 2; }
keep=${ROTATE_KEEP:-5}
dry_run=0
while [ $# -gt 0 ]; do
case $1 in
-k|--keep) [ $# -ge 2 ] || die_usage "$1 needs a value"; keep=$2; shift 2 ;;
--keep=*) keep=${1#*=}; shift ;;
-n|--dry-run) dry_run=1; shift ;;
-h|--help) usage; exit 0 ;;
--) shift; break ;;
-*) die_usage "unknown option: $1" ;;
*) break ;;
esac
done
[ $# -eq 1 ] || die_usage "expected exactly one DIR"
[[ $keep =~ ^[0-9]+$ ]] || die_usage "--keep must be a number, got '$keep'"
dir=$1
[ -d "$dir" ] || { echo "$PROG: no such directory: $dir" >&2; exit 1; }
# newest first (names sort by date here), skip the first $keep
mapfile -t old < <(find "$dir" -maxdepth 1 -type f -printf '%f\n' | sort -r | tail -n +"$((keep + 1))")
for f in "${old[@]}"; do
if [ "$dry_run" -eq 1 ]; then echo "would delete $dir/$f"; else rm -- "$dir/$f"; echo "deleted $dir/$f"; fi
done
echo "kept $(find "$dir" -maxdepth 1 -type f | wc -l) file(s)"
SCRIPT
chmod +x rotate
mkdir backups && touch backups/db-2026-01-0{1..7}.sql.gz
./rotate --keep 2 --dry-run backups; echo "-> $?"
ROTATE_KEEP=4 ./rotate -n backups | tail -n 1; echo "-> $?"
./rotate --keep=three backups; echo "-> $?"
./rotate -k; echo "-> $?"
./rotate --verbose backups; echo "-> $?"
./rotate --keep 5 -- backups; echo "-> $?"would delete backups/db-2026-01-05.sql.gz
would delete backups/db-2026-01-04.sql.gz
would delete backups/db-2026-01-03.sql.gz
would delete backups/db-2026-01-02.sql.gz
would delete backups/db-2026-01-01.sql.gz
kept 7 file(s)
-> 0
kept 7 file(s)
-> 0
rotate: --keep must be a number, got 'three'
Usage: rotate [options] DIR
-k, --keep N keep the newest N files (default: $ROTATE_KEEP or 5)
-n, --dry-run show what would be deleted
-h, --help show this help
-> 2
rotate: -k needs a value
Usage: rotate [options] DIR
-k, --keep N keep the newest N files (default: $ROTATE_KEEP or 5)
-n, --dry-run show what would be deleted
-h, --help show this help
-> 2
rotate: unknown option: --verbose
Usage: rotate [options] DIR
-k, --keep N keep the newest N files (default: $ROTATE_KEEP or 5)
-n, --dry-run show what would be deleted
-h, --help show this help
-> 2
deleted backups/db-2026-01-02.sql.gz
deleted backups/db-2026-01-01.sql.gz
kept 5 file(s)
-> 0
Things worth copying:
- Both
--keep 2and--keep=2. People type both; supporting them costs one extracaseline. --ends the options. Everything after it is a positional argument, even if it starts with-. Pass it on when you call other tools with user input:rm -- "$file",grep -- "$pattern" file.- Validate early.
--keep threefails before anything is deleted, with exit status 2 and a message that names the bad value. - Precedence: flag > environment > default.
keep=${ROTATE_KEEP:-5}before the loop and the flag inside it give exactly that order. Environment variables are how containers and CI pass configuration; flags are how humans override it for one run. - Help goes to stdout with status 0 when asked for, and to stderr with status 2 after a usage error.
Reading data: files, stdin and "-"
Tools compose when they read stdin when no file is given, and treat - as "stdin":
cat > count-errors <<'SCRIPT'
#!/usr/bin/env bash
set -euo pipefail
input=${1:--} # default to "-"
if [ "$input" = - ]; then input=/dev/fd/0; fi # "-" means standard input
{ grep -c ' ERROR ' "$input" || true; }
SCRIPT
chmod +x count-errors
printf '10:00 INFO start\n10:01 ERROR disk full\n10:02 ERROR disk full\n' > app.log
./count-errors app.log
./count-errors < app.log
grep 10:02 app.log | ./count-errors -2
2
1
Exit codes callers can use
| Status | Meaning | Who uses it |
|---|---|---|
| 0 | success | everyone |
| 1 | general failure: the work could not be done | most tools |
| 2 | usage error: bad options or arguments | Bash builtins, grep, diff, most CLIs |
| 3–63 | your own documented failure classes (e.g. 3 = "checks failed", 4 = "dependency down") | monitoring wrappers, CI |
| 75 | temporary failure, try again later (EX_TEMPFAIL) |
schedulers, mail systems |
| 124 | the command timed out (timeout) |
timeout, CI wrappers |
| 126 / 127 | found but not executable / command not found | the shell |
| 128 + N | killed by signal N (130 Ctrl+C, 137 kill -9, 143 SIGTERM) |
the shell |
Document any status beyond 0, 1 and 2 in the help text. Nagios-style monitoring plugins use their own fixed set (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN), so a check script written for one of those systems must follow it instead.
Test yourself
What does -- mean on a command line?
- Decrement a counter
- The end of options: everything after it is a positional argument, even if it starts with
- - Read from stdin
- Run in quiet mode
With keep=${ROTATE_KEEP:-5} before the option loop, what is keep for ROTATE_KEEP=4 ./rotate --keep 2 dir?
- 5
- 4
- 2
- an error
Which exit status conventionally signals a usage error?
- 0
- 1
- 2
- 127