Validating Required Arguments
Parsing (lesson 127) tells a script which arguments it received. Validation checks whether those arguments are acceptable: whether everything required is present, whether each value has the right form, and whether the files and folders they name are usable. A script that skips validation fails later and in confusing ways, for example deep inside a loop, after it has already changed some files, or with a message from cp or find that does not mention the argument the user actually got wrong.
Good validation happens early, before the script does any real work, and it produces messages that point at the exact argument and the rule it broke.
Checking the Number of Arguments
The most basic requirement is the number of operands. $# holds the count (lesson 43), and an arithmetic test compares it:
prog=${0##*/}
if (( $# != 2 )); then
printf 'usage: %s SOURCE DEST\n' "$prog" >&2
exit 2
fi
echo "copying [$1] to [$2]"
$ bash count.sh a
usage: count.sh SOURCE DEST
$ bash count.sh a b c
usage: count.sh SOURCE DEST
$ bash count.sh a b
copying [a] to [b]
The first two runs ended with status 2, the conventional status for incorrect usage (lesson 116), and printed the usage line on standard error (lesson 125). Rejecting too many arguments is as important as rejecting too few: a user who types count.sh a b c probably meant something different, and silently ignoring c hides that.
Use != when the count is fixed, < N when there is a minimum, and both a minimum and a maximum when a range is allowed.
An Empty Argument Still Counts
$# counts arguments, not non-empty arguments. An empty string passes the count check:
$ bash count.sh "" b
copying [] to [b]
Empty arguments happen more often than you might expect, usually when a caller passes an unset variable in quotes, as in count.sh "$SRC" "$DEST". When an empty value makes no sense, test for it explicitly with [[ -z $1 ]] or with the :? expansion below.
The ${parameter:?message} Shortcut
Parameter expansion (lesson 45) has a form that stops the script when a value is missing or empty:
src=${1:?missing SOURCE argument}
dest=${2:?missing DEST argument}
echo "copying [$src] to [$dest]"
$ bash q.sh
q.sh: line 1: 1: missing SOURCE argument
$ bash q.sh a
q.sh: line 2: 2: missing DEST argument
$ bash q.sh "" b
q.sh: line 1: 1: missing SOURCE argument
Each failing run ended with status 1. With the colon, an empty value is rejected as well as a missing one; without it (${1?message}), only a missing argument is. The form is compact, which makes it popular for quick scripts and for required environment variables:
: "${API_URL:?environment variable API_URL must be set}"
echo "using $API_URL"
$ bash q2.sh
q2.sh: line 1: API_URL: environment variable API_URL must be set
$ API_URL=https://api.example.com bash q2.sh
using https://api.example.com
The : command does nothing with its arguments, so the line exists only to trigger the check.
The shortcut has limits. The message always includes the line number and the parameter name (1: above), which reads oddly to a user who does not know the script's internals. The exit status is 1, not the usage status 2. And it cannot print a usage line. For scripts that other people run, an explicit if with a proper message is friendlier; :? is best for environment variables and internal assumptions.
Rejecting Blank Values
A value consisting only of spaces passes [[ -n $1 ]], but it is rarely a valid name. Removing all whitespace with ${name//[[:space:]]/} (lesson 54) and checking whether anything is left catches both empty and blank values:
prog=${0##*/}
name=$1
if [[ -z ${name//[[:space:]]/} ]]; then
printf '%s: NAME must not be empty or blank\n' "$prog" >&2; exit 2
fi
echo "hello [$name]"
$ bash empty.sh ""
empty.sh: NAME must not be empty or blank
$ bash empty.sh " "
empty.sh: NAME must not be empty or blank
$ bash empty.sh " ana "
hello [ ana ]
The original value is not changed; the check only looks at a copy with the whitespace removed. Whether surrounding spaces should be kept, trimmed or rejected depends on what the value is for.
Validating Numbers
Bash variables are strings, so a number is just a string that happens to contain digits. Arithmetic on a non-numeric string does not fail cleanly: Bash treats a word such as abc as a variable name (usually evaluating to 0), and a string such as 12abc causes an arithmetic error at the point of use. Checking the format first with a regular expression (lesson 69) keeps the error at the start of the script:
is_uint() { [[ $1 =~ ^[0-9]+$ ]]; }
is_int() { [[ $1 =~ ^-?[0-9]+$ ]]; }
for v in 42 007 -3 3.5 12abc "" " 7" 99999999999999999999; do
printf '%-22s uint=%s int=%s\n' "[$v]" "$(is_uint "$v" && echo yes || echo no)" "$(is_int "$v" && echo yes || echo no)"
done
[42] uint=yes int=yes
[007] uint=yes int=yes
[-3] uint=no int=yes
[3.5] uint=no int=no
[12abc] uint=no int=no
[] uint=no int=no
[ 7] uint=no int=no
[99999999999999999999] uint=yes int=yes
The anchors ^ and $ require the whole value to match, so 12abc and 7 are rejected. Two results need attention: 007 and the very long number.
Leading Zeros and Ranges
Bash reads a number with a leading zero as octal, so 08 causes an error in arithmetic:
range.sh: line 9: ((: 08: value too great for base (error token is "08")
The prefix 10# forces base 10 (lesson 73). With it, a range check accepts user input such as 08 and compares the intended value:
check_days() {
local v=$1
[[ $v =~ ^[0-9]+$ ]] || { echo "[$v] not a whole number"; return 1; }
(( 10#$v >= 1 && 10#$v <= 365 )) || { echo "[$v] out of range 1-365"; return 1; }
echo "[$v] ok ($((10#$v)))"
}
for v in 30 0 400 08 365 x; do check_days "$v"; done
[30] ok (30)
[0] out of range 1-365
[400] out of range 1-365
[08] ok (8)
[365] ok (365)
[x] not a whole number
Very Long Numbers Overflow
Bash arithmetic uses 64-bit integers, and a number with too many digits silently wraps around instead of producing an error:
$ v=18446744073709551617; echo $(( 10#$v ))
1
The 20-digit input became 1, which passes a 1 to 365 range check. Limiting the number of digits in the pattern, for example ^[0-9]{1,9}$, rejects such values before any arithmetic happens. The complete example below uses this technique.
Validating a Choice from a Fixed List
When a value must be one of a few words, a case statement (lesson 75) is the clearest check:
for m in copy move Copy delete ""; do
case $m in
copy|move) echo "[$m] ok" ;;
*) echo "[$m] must be 'copy' or 'move'" ;;
esac
done
[copy] ok
[move] ok
[Copy] must be 'copy' or 'move'
[delete] must be 'copy' or 'move'
[] must be 'copy' or 'move'
Matching is case-sensitive. Listing the allowed values in the message saves the user a trip to the documentation.
Validating Files and Directories
When an argument names a file or folder, the file test operators (lessons 71 and 72) check it. The order of the tests matters, because each test narrows down the reason for a failure:
check_src() {
local d=$1
[[ -e $d ]] || { echo "'$d' does not exist"; return 1; }
[[ -d $d ]] || { echo "'$d' is not a directory"; return 1; }
[[ -r $d && -x $d ]] || { echo "'$d' cannot be read"; return 1; }
echo "'$d' ok as source"
}
check_dest() {
local d=$1
[[ -d $d ]] || { echo "'$d' is not an existing directory"; return 1; }
[[ -w $d ]] || { echo "'$d' is not writable"; return 1; }
echo "'$d' ok as destination"
}
for d in logs nowhere notes.txt; do check_src "$d"; done
for d in logs ro; do check_dest "$d"; done
Run as an ordinary user, in a folder where logs and ro belong to another user and ro has mode 555:
'logs' ok as source
'nowhere' does not exist
'notes.txt' is not a directory
'logs' is not writable
'ro' is not writable
Testing -e before -d lets the script say "does not exist" instead of the less precise "is not a directory". For a folder, read permission (-r) allows listing its contents and execute permission (-x) allows entering it, so a source folder needs both. One caution: the root user bypasses permission checks, so run as root, the same script reported both folders as writable. Test permission handling as an ordinary user.
These checks describe the moment they run. Another process can delete or change a file between the check and its use, so a script must still handle a failing cp or mv later. Early checks exist to give clear messages for the common case, not to guarantee success.
Validating Formats Beyond Simple Patterns
A regular expression can check the shape of a value, but not always its meaning. A date pattern ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ accepts 2026-02-30, which does not exist. Combining the pattern with a tool that understands dates, here GNU date -d, checks both:
valid_date() {
[[ $1 =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || return 1
date -d "$1" +%F >/dev/null 2>&1
}
for d in 2026-11-22 2026-02-30 2026-13-01 22-11-2026 2026-1-5 "2026-11-22 extra"; do
valid_date "$d" && echo "[$d] valid" || echo "[$d] invalid"
done
[2026-11-22] valid
[2026-02-30] invalid
[2026-13-01] invalid
[22-11-2026] invalid
[2026-1-5] invalid
[2026-11-22 extra] invalid
The pattern enforces one exact format, and date rejects impossible calendar dates (it printed date: invalid date '2026-02-30' with status 1, hidden here by the redirection). The -d option belongs to GNU date; BSD and macOS date use different options.
Failing Fast or Reporting Everything
There are two reasonable strategies when several arguments are wrong:
- Fail fast: stop at the first problem. This is simple, and appropriate when later checks depend on earlier ones (there is no point checking whether a folder is writable if it does not exist).
- Collect and report: check every independent rule, store the messages, and print them all before exiting. The user can fix everything in one attempt instead of discovering problems one at a time.
The second strategy fits usage errors well, because they are independent of each other and cost nothing to check. When printing the collected messages, loop over them; a single printf '%s: %s\n' "$prog" "${errors[@]}" would reuse the format for pairs of arguments and pair the second message with the third:
prog: first problem
second problem: third problem
A Complete Example
archive-old.sh copies or moves files older than a number of days from one folder to another. Every argument is required. It distinguishes usage errors (wrong or missing arguments, status 2, all reported together with the usage line) from environment errors (the arguments are well formed but the folders are not usable, status 1, reported one at a time), and it validates everything before touching any file.
#!/usr/bin/env bash
# archive-old.sh -d DAYS -m copy|move SOURCE_DIR DEST_DIR
set -euo pipefail
prog=${0##*/}
usage() { printf 'usage: %s -d DAYS -m copy|move SOURCE_DIR DEST_DIR\n' "$prog"; }
days= mode=
operands=()
while (( $# > 0 )); do
case $1 in
-h|--help) usage; exit 0 ;;
-d|--days|-m|--mode)
if (( $# < 2 )); then
printf "%s: option '%s' requires an argument\n" "$prog" "$1" >&2
exit 2
fi
case $1 in -d|--days) days=$2 ;; *) mode=$2 ;; esac
shift ;;
--) shift; operands+=("$@"); break ;;
-*) printf "%s: unrecognized option '%s'\n" "$prog" "$1" >&2; exit 2 ;;
*) operands+=("$1") ;;
esac
shift
done
# ---- validation: collect every problem, then report them together ----
errors=()
if [[ -z $days ]]; then
errors+=("missing required option -d DAYS")
elif [[ ! $days =~ ^[0-9]{1,4}$ ]] || (( 10#$days < 1 || 10#$days > 3650 )); then
errors+=("DAYS must be a whole number from 1 to 3650, got '$days'")
fi
case $mode in
copy|move) ;;
"") errors+=("missing required option -m copy|move") ;;
*) errors+=("mode must be 'copy' or 'move', got '$mode'") ;;
esac
if (( ${#operands[@]} != 2 )); then
errors+=("expected SOURCE_DIR and DEST_DIR, got ${#operands[@]} operand(s)")
fi
if (( ${#errors[@]} > 0 )); then
for e in "${errors[@]}"; do printf '%s: %s\n' "$prog" "$e" >&2; done
usage >&2
exit 2
fi
src=${operands[0]} dest=${operands[1]}
# ---- checks on the file system: these are not usage errors ----
[[ -d $src ]] || { printf "%s: source '%s' is not a directory\n" "$prog" "$src" >&2; exit 1; }
[[ -d $dest ]] || { printf "%s: destination '%s' is not a directory\n" "$prog" "$dest" >&2; exit 1; }
[[ -w $dest ]] || { printf "%s: destination '%s' is not writable\n" "$prog" "$dest" >&2; exit 1; }
[[ $(cd -- "$src" && pwd -P) != "$(cd -- "$dest" && pwd -P)" ]] \
|| { printf '%s: SOURCE_DIR and DEST_DIR are the same folder\n' "$prog" >&2; exit 2; }
days=$((10#$days))
count=0
while IFS= read -r -d '' file; do
if [[ $mode == copy ]]; then cp -p -- "$file" "$dest"/; else mv -- "$file" "$dest"/; fi
printf '%s %s\n' "$mode" "${file##*/}"
count=$((count + 1))
done < <(find "$src" -maxdepth 1 -type f -mtime +"$((days - 1))" -print0 | sort -z)
printf '%s: %d file(s) older than %d day(s) handled\n' "$prog" "$count" "$days"
How the Validation Works
- Required options are detected by an empty variable.
daysandmodestart empty, so after parsing, an empty value means the option was never given. (If an empty value were meaningful, a separate flag variable would be needed; lesson 129 shows this.) elifmakes the format check run only when a value exists, so a missing option produces one clear message instead of two.^[0-9]{1,4}$rejects signs, decimals and overflowing numbers before10#arithmetic runs. The range check then enforces 1 to 3650.- The operand count is checked after parsing, because operands can appear between options.
- The same-folder check compares physical paths:
cd -- "$dir" && pwd -Presolveslogs/,./logsand symbolic links to one canonical path. Copying a folder onto itself would do nothing useful, and moving files onto themselves could be harmful, so this case is treated as incorrect usage. days=$((10#$days))normalizes a value like007to7before it is used in thefindexpression and the final message.-mtime +Ninfindmatches files whose age in whole days is greater than N, so+29selects files at least 30 days old.
Running the Complete Example
The folder logs holds jan.log (40 days old), old report.log (10 days old) and today.log; archive is empty.
Running with nothing reports every missing piece at once:
$ bash archive-old.sh
archive-old.sh: missing required option -d DAYS
archive-old.sh: missing required option -m copy|move
archive-old.sh: expected SOURCE_DIR and DEST_DIR, got 0 operand(s)
usage: archive-old.sh -d DAYS -m copy|move SOURCE_DIR DEST_DIR
Wrong values are named exactly:
$ bash archive-old.sh -d abc -m delete logs
archive-old.sh: DAYS must be a whole number from 1 to 3650, got 'abc'
archive-old.sh: mode must be 'copy' or 'move', got 'delete'
archive-old.sh: expected SOURCE_DIR and DEST_DIR, got 1 operand(s)
usage: archive-old.sh -d DAYS -m copy|move SOURCE_DIR DEST_DIR
When the user forgets the value of -d, the parser takes the next word as the value, and validation then explains the consequences:
$ bash archive-old.sh -d -m copy logs archive
archive-old.sh: DAYS must be a whole number from 1 to 3650, got '-m'
archive-old.sh: missing required option -m copy|move
archive-old.sh: expected SOURCE_DIR and DEST_DIR, got 3 operand(s)
usage: archive-old.sh -d DAYS -m copy|move SOURCE_DIR DEST_DIR
The first message, got '-m', shows the user what happened. Every run so far ended with status 2 without touching a file.
Well-formed arguments that point to unusable folders produce environment errors:
$ bash archive-old.sh -d 30 -m copy logs nowhere
archive-old.sh: destination 'nowhere' is not a directory
$ bash archive-old.sh -d 30 -m copy logs/ ./logs
archive-old.sh: SOURCE_DIR and DEST_DIR are the same folder
The first ended with status 1, the second with status 2. Run by an ordinary user with a destination folder owned by root, the script printed archive-old.sh: destination 'dst' is not writable with status 1.
Finally, valid runs:
$ bash archive-old.sh -d 30 -m copy logs archive
copy jan.log
archive-old.sh: 1 file(s) older than 30 day(s) handled
$ bash archive-old.sh --days 7 --mode move logs archive
move jan.log
move old report.log
archive-old.sh: 2 file(s) older than 7 day(s) handled
After the second run, logs contains only today.log, and the file name with a space was handled correctly because the list of files travels through find -print0 and read -d '' (lesson 112).