Linux and servers · Intermediate · 18 min
Parse options and validate input in Bash scripts with getopts
By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · Bash 5.3
You will turn a backup-pruning script into a proper command-line tool with getopts, a usage message, checked input, long options and an env file for defaults, then prove it with a test script.
On this page
A script that deletes files needs a careful front door. If it reads $1 and $2 and trusts them, a swapped argument or a typo in a cron line can make it delete the wrong things, or nothing, without saying so. In this tutorial you build prune-backups.sh, which keeps the newest backups in a directory and deletes the rest, and give it a command line you can trust:
-nfor a dry run,-k <count>for how many to keep,-vfor detail and-hfor help, parsed with thegetoptsbuiltin- a usage message on stderr and exit code 2 for any bad input, before a single file is touched
- long options such as
--dry-runand--keep=5 - defaults read from an env file, without running the file as code
- a test script that runs it with good and bad arguments
All the work happens in ~/prune-demo, which you delete at the end. Every command after the first step runs from inside that directory.
Step 1 · Make practice backups and see why positional arguments fail
Check your Bash version. The script uses mapfile -d, which needs Bash 4.4 or later:
bash --version | head -n 1Ubuntu 26.04 prints GNU bash, version 5.3 followed by a patch level.
Create a directory of fake backups. The names carry the date, so sorting by name puts the oldest first. A text file sits alongside them, and the script must leave it alone:
mkdir -p ~/prune-demo/backups
cd ~/prune-demo
for day in 01 02 03 04 05 06 07 08 09 10; do
touch "backups/app-2026-11-$day.tar.gz"
done
touch backups/notes.txt
ls backupsHere is a first version that takes the directory and the count as positional arguments. It only counts, and deletes nothing yet:
cat > prune-backups.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
dir=$1
keep=${2:-7}
mapfile -d '' -t backups < <(
find "$dir" -maxdepth 1 -type f -name '*.tar.gz' -print0 | LC_ALL=C sort -z
)
printf 'found %d backups in %s, would keep %s\n' "${#backups[@]}" "$dir" "$keep"
EOF
chmod +x prune-backups.sh
./prune-backups.sh backups 3find -print0 and mapfile -d '' pass the names separated by null bytes, so file names with spaces survive. LC_ALL=C makes the sort order the same on every machine, whatever its language settings.
Now call it the way someone in a hurry might, with the arguments swapped, and then with none:
./prune-backups.sh 3 backups
./prune-backups.sh || echo "exit code $?"Check it worked
The first good call prints found 10 backups in backups, would keep 3. The swapped call prints a find error, then found 0 backups in 3, would keep backups, and still exits 0: the script carried on with nonsense. The call with no arguments stops with something like line 4: $1: unbound variable and a non-zero exit code, which tells the person running it nothing about how to use it. The rest of this tutorial fixes both.
Step 2 · Parse short options with getopts
getopts is a shell builtin. You give it a string of option letters, and a letter followed by : takes a value. Each time round a while loop it puts the next option letter in a variable and, for options that take a value, the value in OPTARG. When it reaches the first argument that is not an option, it stops and leaves OPTIND pointing at it, so shift $((OPTIND - 1)) leaves only the positional arguments in $@.
A : at the start of the string turns on silent mode. getopts then prints nothing itself and tells you what went wrong instead: ? for an unknown option and : for a missing value, with the option letter in OPTARG. That way every error goes through your own message.
Replace the script with this version. It parses -n, -k, -v and -h, prints usage, validates its input and then prunes:
cat > prune-backups.sh <<'EOF'
#!/usr/bin/env bash
# prune-backups.sh: keep the newest backups in a directory, delete the rest.
set -euo pipefail
prog=${0##*/}
dry_run=0
verbose=0
keep=7
usage() {
cat <<USAGE
Usage: $prog [-n] [-v] [-k count] directory
Delete all but the newest *.tar.gz backups in directory.
-n dry run: list what would be deleted, delete nothing
-k count how many backups to keep (default: 7)
-v report each file kept or deleted on stderr
-h show this help
USAGE
}
die_usage() {
printf '%s: %s\n' "$prog" "$1" >&2
usage >&2
exit 2
}
die() {
printf '%s: %s\n' "$prog" "$1" >&2
exit 1
}
say() {
if (( verbose )); then
printf '%s\n' "$1" >&2
fi
}
while getopts ':nk:vh' opt; do
case $opt in
n) dry_run=1 ;;
k) keep=$OPTARG ;;
v) verbose=1 ;;
h) usage; exit 0 ;;
:) die_usage "option -$OPTARG needs a value" ;;
\?) die_usage "unknown option -$OPTARG" ;;
esac
done
shift $((OPTIND - 1))
(( $# == 1 )) || die_usage "expected one directory, got $#"
dir=$1
# Validate everything before touching a file.
[[ $keep =~ ^[0-9]{1,4}$ ]] || die_usage "keep count must be a whole number from 1 to 9999, got '$keep'"
keep=$((10#$keep))
(( keep >= 1 )) || die_usage "keep count must be a whole number from 1 to 9999, got '$keep'"
[[ -d $dir ]] || die "not a directory: $dir"
dir=$(realpath -- "$dir")
[[ $dir != / ]] || die "refusing to prune /"
mapfile -d '' -t backups < <(
find "$dir" -maxdepth 1 -type f -name '*.tar.gz' -print0 | LC_ALL=C sort -z
)
total=${#backups[@]}
if (( total <= keep )); then
printf 'nothing to delete: %d backups in %s, keeping up to %d\n' "$total" "$dir" "$keep"
exit 0
fi
remove=$((total - keep))
for file in "${backups[@]:0:remove}"; do
if (( dry_run )); then
printf 'would delete %s\n' "$file"
else
say "deleting $file"
rm -- "$file"
fi
done
for file in "${backups[@]:remove}"; do
say "keeping $file"
done
if (( dry_run )); then
printf 'dry run: would delete %d of %d backups in %s\n' "$remove" "$total" "$dir"
else
printf 'deleted %d of %d backups in %s\n' "$remove" "$total" "$dir"
fi
EOF
./prune-backups.sh -h
./prune-backups.sh -n -k 3 backupsA few choices in this script are deliberate:
- Help asked for with
-hgoes to stdout with exit code 0, because the person wanted it. Usage printed because of a mistake goes to stderr with exit code 2, the code Bash's own builtins use for incorrect usage. A cron job or a wrapper script can then tell "you called me wrongly" (2) from "something failed while working" (1). - Messages for the operator, such as
-voutput, go to stderr. Stdout carries only the result, so it can be piped or logged on its own. getoptsaccepts the usual short forms:-n -k 3,-nk3and-nk 3all mean the same thing.
Check it worked
-h prints the usage text and returns you to the prompt. The dry run lists seven would delete lines, from app-2026-11-01.tar.gz to app-2026-11-07.tar.gz, each with its full path, and ends with dry run: would delete 7 of 10 backups in /home/<you>/prune-demo/backups. ls backups still shows all ten backups and notes.txt.
Step 3 · Reject bad input before anything is deleted
The validation block sits between parsing and the first find, so no bad value reaches the code that deletes. It checks:
- The count is one to four digits. The regular expression rejects
abc,-3,2.5and an empty value.10#$keepthen reads it as base 10, because Bash arithmetic treats a leading zero as octal and would fail on08. - The count is at least 1. A count of 0 would delete every backup, which is never what a pruning job should do by accident.
- The directory exists.
realpathturns it into an absolute path with no..or symbolic links left, so the messages show exactly what is being pruned, and the script refuses to work on/.
Try the mistakes people make. Each one should stop with a message and a non-zero exit code:
./prune-backups.sh -k abc backups || echo "exit code $?"
./prune-backups.sh -k 0 backups || echo "exit code $?"
./prune-backups.sh -k || echo "exit code $?"
./prune-backups.sh -x backups || echo "exit code $?"
./prune-backups.sh backups -k 3 || echo "exit code $?"
./prune-backups.sh -k 3 /no/such/dir || echo "exit code $?"The fifth call is worth a closer look. getopts stops at the first argument that is not an option, so backups -k 3 leaves three positional arguments and the script rejects it. Put options before the directory.
Once you trust it, run it for real with -v to see each decision:
./prune-backups.sh -v -k 3 backups
ls backupsCheck it worked
The first five bad calls each print a prune-backups.sh: line naming the problem, such as keep count must be a whole number from 1 to 9999, got 'abc' or option -k needs a value, then the usage text, then exit code 2. The missing directory prints not a directory: /no/such/dir and exit code 1, without the usage text. The real run prints seven deleting and three keeping lines, then deleted 7 of 10 backups, and ls backups shows app-2026-11-08.tar.gz, app-2026-11-09.tar.gz, app-2026-11-10.tar.gz and notes.txt.
Step 4 · Read defaults from an env file
A server usually runs the script from cron with the same settings every night. Keeping those settings in a file means the cron line stays short and the values can change without editing the script. The obvious way to read such a file is source, but source runs every line as Bash. A file containing KEEP=$(curl ... | sh) would run that command as whoever runs the script, which for a backup job is often root.
This version reads the file as data instead. It splits each line at the first =, accepts only the two names it knows, ignores blank lines and # comments, strips one pair of surrounding double quotes and rejects anything else. The order of precedence is: built-in defaults, then the env file, then the command line. Because the file is read before getopts runs, -k always wins, and because validation runs after both, a bad value from the file is caught by the same checks.
The file's location comes from PRUNE_BACKUPS_ENV, with /etc/default/prune-backups as the default. The directory argument becomes optional when the file sets BACKUP_DIR.
Make ten backups again, then replace the script:
for day in 01 02 03 04 05 06 07 08 09 10; do
touch "backups/app-2026-11-$day.tar.gz"
done
cat > prune-backups.sh <<'EOF'
#!/usr/bin/env bash
# prune-backups.sh: keep the newest backups in a directory, delete the rest.
set -euo pipefail
prog=${0##*/}
dry_run=0
verbose=0
keep=7
dir=''
env_file=${PRUNE_BACKUPS_ENV:-/etc/default/prune-backups}
usage() {
cat <<USAGE
Usage: $prog [-n] [-v] [-k count] [directory]
Delete all but the newest *.tar.gz backups in directory.
Defaults are read from $env_file (KEEP, BACKUP_DIR).
-n dry run: list what would be deleted, delete nothing
-k count how many backups to keep (default: 7, or KEEP)
-v report each file kept or deleted on stderr
-h show this help
USAGE
}
die_usage() {
printf '%s: %s\n' "$prog" "$1" >&2
usage >&2
exit 2
}
die() {
printf '%s: %s\n' "$prog" "$1" >&2
exit 1
}
say() {
if (( verbose )); then
printf '%s\n' "$1" >&2
fi
}
# Read KEY=value lines as data. Never source this file.
load_env() {
local key value
[[ -f $env_file ]] || return 0
while IFS='=' read -r key value || [[ -n $key ]]; do
value=${value%\"}
value=${value#\"}
case $key in
'' | '#'*) ;;
KEEP) keep=$value ;;
BACKUP_DIR) dir=$value ;;
*) die "$env_file: unknown setting '$key'" ;;
esac
done < "$env_file"
}
load_env
while getopts ':nk:vh' opt; do
case $opt in
n) dry_run=1 ;;
k) keep=$OPTARG ;;
v) verbose=1 ;;
h) usage; exit 0 ;;
:) die_usage "option -$OPTARG needs a value" ;;
\?) die_usage "unknown option -$OPTARG" ;;
esac
done
shift $((OPTIND - 1))
(( $# <= 1 )) || die_usage "expected one directory, got $#"
if (( $# == 1 )); then
dir=$1
fi
[[ -n $dir ]] || die_usage "no directory given and no BACKUP_DIR in $env_file"
# Validate everything before touching a file.
[[ $keep =~ ^[0-9]{1,4}$ ]] || die_usage "keep count must be a whole number from 1 to 9999, got '$keep'"
keep=$((10#$keep))
(( keep >= 1 )) || die_usage "keep count must be a whole number from 1 to 9999, got '$keep'"
[[ -d $dir ]] || die "not a directory: $dir"
dir=$(realpath -- "$dir")
[[ $dir != / ]] || die "refusing to prune /"
mapfile -d '' -t backups < <(
find "$dir" -maxdepth 1 -type f -name '*.tar.gz' -print0 | LC_ALL=C sort -z
)
total=${#backups[@]}
if (( total <= keep )); then
printf 'nothing to delete: %d backups in %s, keeping up to %d\n' "$total" "$dir" "$keep"
exit 0
fi
remove=$((total - keep))
for file in "${backups[@]:0:remove}"; do
if (( dry_run )); then
printf 'would delete %s\n' "$file"
else
say "deleting $file"
rm -- "$file"
fi
done
for file in "${backups[@]:remove}"; do
say "keeping $file"
done
if (( dry_run )); then
printf 'dry run: would delete %d of %d backups in %s\n' "$remove" "$total" "$dir"
else
printf 'deleted %d of %d backups in %s\n' "$remove" "$total" "$dir"
fi
EOFWrite an env file for the demo. The heredoc delimiter is unquoted here on purpose, so $HOME expands to your real home directory: the script does not expand ~ or variables inside the file.
cat > prune.env <<EOF
# Defaults for prune-backups.sh. Command-line options win.
KEEP=5
BACKUP_DIR=$HOME/prune-demo/backups
EOF
cat prune.env
PRUNE_BACKUPS_ENV=./prune.env ./prune-backups.sh -n
PRUNE_BACKUPS_ENV=./prune.env ./prune-backups.sh -n -k 8Now prove the file is never run as code, and that a typo is caught rather than ignored:
printf 'KEEP=$(date)\n' > bad.env
PRUNE_BACKUPS_ENV=./bad.env ./prune-backups.sh -n backups || echo "exit code $?"
printf 'KEPP=4\n' > bad.env
PRUNE_BACKUPS_ENV=./bad.env ./prune-backups.sh -n backups || echo "exit code $?"On a server you would put the settings in /etc/default/prune-backups, owned by root and not writable by anyone else, since the script trusts its values.
Check it worked
The first dry run, with no options but the file, ends with dry run: would delete 5 of 10 backups. Adding -k 8 overrides the file and gives would delete 2 of 10. The $(date) file is rejected with got '$(date)' and exit code 2, which shows the text was read literally and no date was printed. The KEPP typo stops with ./bad.env: unknown setting 'KEPP' and exit code 1.
Step 5 · Accept long options
getopts only knows single-letter options, and that is part of the POSIX standard rather than a Bash gap. You may see scripts use the external getopt command instead (no s). The enhanced getopt from util-linux on Linux does handle long options, but the traditional getopt found on macOS and the BSDs does not, and it breaks arguments that contain spaces. A script built on it behaves differently depending on which one is installed. getopts is built into the shell and behaves the same everywhere Bash runs.
To get long options without that risk, translate them into short ones with a while/case loop and hand the result to getopts. The loop handles --keep 5 and --keep=5, stops translating at -- so a directory whose name starts with a dash still works, and rejects any long option it does not know.
The script gets one new block, between load_env and the getopts loop. Rewrite the file in full so there is no hand-editing to get wrong. This is the finished script:
cat > prune-backups.sh <<'EOF'
#!/usr/bin/env bash
# prune-backups.sh: keep the newest backups in a directory, delete the rest.
set -euo pipefail
prog=${0##*/}
dry_run=0
verbose=0
keep=7
dir=''
env_file=${PRUNE_BACKUPS_ENV:-/etc/default/prune-backups}
usage() {
cat <<USAGE
Usage: $prog [options] [directory]
Delete all but the newest *.tar.gz backups in directory.
Defaults are read from $env_file (KEEP, BACKUP_DIR).
-n, --dry-run list what would be deleted, delete nothing
-k, --keep COUNT how many backups to keep (default: 7, or KEEP)
-v, --verbose report each file kept or deleted on stderr
-h, --help show this help
USAGE
}
die_usage() {
printf '%s: %s\n' "$prog" "$1" >&2
usage >&2
exit 2
}
die() {
printf '%s: %s\n' "$prog" "$1" >&2
exit 1
}
say() {
if (( verbose )); then
printf '%s\n' "$1" >&2
fi
}
# Read KEY=value lines as data. Never source this file.
load_env() {
local key value
[[ -f $env_file ]] || return 0
while IFS='=' read -r key value || [[ -n $key ]]; do
value=${value%\"}
value=${value#\"}
case $key in
'' | '#'*) ;;
KEEP) keep=$value ;;
BACKUP_DIR) dir=$value ;;
*) die "$env_file: unknown setting '$key'" ;;
esac
done < "$env_file"
}
load_env
# Translate long options into short ones, then let getopts do the parsing.
args=()
while (( $# )); do
case $1 in
--dry-run) args+=(-n) ;;
--verbose) args+=(-v) ;;
--help) args+=(-h) ;;
--keep=*) args+=(-k "${1#*=}") ;;
--keep)
(( $# >= 2 )) || die_usage "option --keep needs a value"
args+=(-k "$2")
shift
;;
--) args+=("$@"); break ;;
--*) die_usage "unknown option $1" ;;
*) args+=("$1") ;;
esac
shift
done
set -- "${args[@]}"
while getopts ':nk:vh' opt; do
case $opt in
n) dry_run=1 ;;
k) keep=$OPTARG ;;
v) verbose=1 ;;
h) usage; exit 0 ;;
:) die_usage "option -$OPTARG needs a value" ;;
\?) die_usage "unknown option -$OPTARG" ;;
esac
done
shift $((OPTIND - 1))
(( $# <= 1 )) || die_usage "expected one directory, got $#"
if (( $# == 1 )); then
dir=$1
fi
[[ -n $dir ]] || die_usage "no directory given and no BACKUP_DIR in $env_file"
# Validate everything before touching a file.
[[ $keep =~ ^[0-9]{1,4}$ ]] || die_usage "keep count must be a whole number from 1 to 9999, got '$keep'"
keep=$((10#$keep))
(( keep >= 1 )) || die_usage "keep count must be a whole number from 1 to 9999, got '$keep'"
[[ -d $dir ]] || die "not a directory: $dir"
dir=$(realpath -- "$dir")
[[ $dir != / ]] || die "refusing to prune /"
mapfile -d '' -t backups < <(
find "$dir" -maxdepth 1 -type f -name '*.tar.gz' -print0 | LC_ALL=C sort -z
)
total=${#backups[@]}
if (( total <= keep )); then
printf 'nothing to delete: %d backups in %s, keeping up to %d\n' "$total" "$dir" "$keep"
exit 0
fi
remove=$((total - keep))
for file in "${backups[@]:0:remove}"; do
if (( dry_run )); then
printf 'would delete %s\n' "$file"
else
say "deleting $file"
rm -- "$file"
fi
done
for file in "${backups[@]:remove}"; do
say "keeping $file"
done
if (( dry_run )); then
printf 'dry run: would delete %d of %d backups in %s\n' "$remove" "$total" "$dir"
else
printf 'deleted %d of %d backups in %s\n' "$remove" "$total" "$dir"
fi
EOF
./prune-backups.sh --dry-run --keep=4 backups
./prune-backups.sh --dry-run --keep 4 --verbose backups
./prune-backups.sh --kep 4 backups || echo "exit code $?"Long and short forms mix freely, so -n --keep 4 works too.
Check it worked
Both dry runs end with dry run: would delete 6 of 10 backups. The --verbose run adds four keeping lines, which come from stderr: run it again with 2>/dev/null and they disappear while the would delete lines stay. The misspelt --kep prints unknown option --kep, the usage text and exit code 2.
Step 6 · Test the script with good and bad arguments
Checking a handful of calls by eye is fine once. Every later change to the script deserves the same checks, so write them down. This test script builds a fresh set of backups in a temporary directory, runs the real script with each kind of argument, compares the exit code with what it should be, and checks that only the right files were deleted. It points PRUNE_BACKUPS_ENV at a file that does not exist, so a defaults file on the machine cannot change the results.
cat > test-prune.sh <<'EOF'
#!/usr/bin/env bash
# test-prune.sh: run prune-backups.sh with good and bad arguments.
set -euo pipefail
cd "$(dirname "$0")"
export PRUNE_BACKUPS_ENV=/nonexistent
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
b=$work/backups
fails=0
make_backups() {
local day
rm -rf "$b"
mkdir "$b"
for day in 01 02 03 04 05 06 07 08 09 10; do
touch "$b/app-2026-11-$day.tar.gz"
done
}
count_backups() {
find "$b" -maxdepth 1 -name '*.tar.gz' | wc -l
}
# expect <exit code> <arguments...>
expect() {
local want=$1 got=0
shift
./prune-backups.sh "$@" > /dev/null 2>&1 || got=$?
if (( got == want )); then
printf 'ok exit %d %s\n' "$got" "$*"
else
printf 'FAIL exit %d, wanted %d %s\n' "$got" "$want" "$*"
fails=$((fails + 1))
fi
}
make_backups
expect 2 -k abc "$b"
expect 2 -k 0 "$b"
expect 2 -k
expect 2 -x "$b"
expect 2 --kep 3 "$b"
expect 2 "$b" extra
expect 2
expect 1 -k 3 "$work/missing"
expect 0 -n -k 3 "$b"
expect 0 --dry-run --keep=3 "$b"
if (( $(count_backups) != 10 )); then
echo "FAIL a bad call or a dry run deleted files"
fails=$((fails + 1))
fi
expect 0 --keep 3 "$b"
if [[ -e $b/app-2026-11-10.tar.gz ]] && (( $(count_backups) == 3 )); then
echo "ok kept the newest 3 backups"
else
echo "FAIL wrong files left after pruning"
fails=$((fails + 1))
fi
if (( fails > 0 )); then
printf '%d test(s) failed\n' "$fails"
exit 1
fi
echo "all tests passed"
EOF
chmod +x test-prune.sh
./test-prune.shCheck it worked
Each line starts with ok and shows the exit code and arguments; the temporary path in them changes on every run. The last two lines are ok kept the newest 3 backups and all tests passed, and the script exits 0. To see a failure, change expect 2 -k 0 "$b" to expect 0 -k 0 "$b" and run it again: that line shows FAIL exit 2, wanted 0 and the script ends with 1 test(s) failed. Change it back afterwards.
When you have finished with the demo, remove it. This deletes the whole ~/prune-demo directory, including the scripts, so copy prune-backups.sh and test-prune.sh somewhere else first if you want to keep them.
cd ~
rm -rf ~/prune-demoNext steps
- Make the rest of the script fail loudly and clean up after itself in /tutorials/write-safer-bash-scripts-with-strict-mode-and-traps.
- Run ShellCheck over
prune-backups.shand fix what it reports with /tutorials/find-bugs-in-shell-scripts-with-shellcheck. - Run the pruning every night with
--keepand a defaults file, using /tutorials/schedule-jobs-with-cron.
Related tutorials
- Write safer Bash scripts with strict mode and trapsYou will build a small Bash release script that stops on the first error, says which line failed, survives file names with spaces and always removes its temporary files.
- Write least-privilege sudo rules with visudoYou will replace blanket sudo access with checked rule files in /etc/sudoers.d that let two operators restart one service and edit one file, give an automation account a password-free command list, and audit what every account can run.
- Upgrade a server from Ubuntu 24.04 LTS to 26.04 LTSYou will take a backed-up Ubuntu 24.04 server through do-release-upgrade to 26.04 LTS over SSH with a fallback login, then confirm services, repositories and language runtimes work on the new release.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials