Setting Defaults for Optional Parameters
An optional parameter is one the user may leave out: an option such as -k KEEP, an operand such as a folder name, or a setting in the environment. When it is left out, the script still needs a value, and that value is the default. Good defaults make a script easy to run (snapshot.sh with no arguments does something sensible), while clear rules about where defaults come from make it predictable (the user can always tell which value is in effect and why).
Lesson 45 introduced the parameter-expansion operators such as ${var:-default}, and lesson 129 showed how a script can tell "not given" apart from "given". This lesson puts them together: how to set defaults for options, operands and arrays, how to layer defaults from several sources in a fixed order of priority, how to compute a default only when it is needed, and how to keep the help text in agreement with the real values.
Two Ways to Write a Default
There are two common patterns, and most scripts use both.
Assign first, override later. The default is assigned before the parsing loop, and the loop replaces it when the option appears:
keep=5 # default
while (( $# > 0 )); do
case $1 in
-k|--keep) keep=$2; shift ;;
esac
shift
done
This is the clearest form for options, because all defaults sit together near the top of the script, where a reader expects them.
Fall back at the point of use. A parameter expansion supplies the default only if the variable has no value:
port=${APP_PORT:-8080} # environment variable or 8080
dir=${1:-.} # first operand or the current folder
This form suits values that come from outside the parsing loop, such as positional parameters and environment variables. It also works under set -u (lesson 120), because a default expansion of an unset variable is not an error:
$ bash -c 'set -u; echo "v=${NOPE:-fallback}"; echo "$NOPE"'
v=fallback
bash: line 1: NOPE: unbound variable
Empty Versus Not Given
The two families of operators differ only in how they treat an empty value:
${u:-def} unset -> [def]
${e:-def} empty -> [def]
${u-def} unset -> [def]
${e-def} empty -> []
With the colon, an empty value is replaced by the default. Without it, only an unset variable is replaced. The assigning forms := and = follow the same rule:
: ${color:=auto} -> [auto]
empty x after := -> [filled]
empty y after = -> []
The : command does nothing; it exists here only so that the expansion runs and assigns the default.
For a script, the question is what an empty value from the user should mean. Consider a script whose --name option defaults to guest, called as --name "":
name=guest
[[ ${1-} == --name ]] && name=$2
echo "A: [${name:-guest}]"
name=${2-guest}
echo "B: [$name]"
$ bash emptyopt.sh --name ""
A: [guest]
B: []
Version A treats the empty value as "use the default", version B keeps the empty string because the user did give the option. Either can be correct, but the choice should be deliberate. A useful rule: for environment variables, use :-, because SNAPSHOT_DEST= usually means "not set" in practice; for options, decide case by case and reject an empty value during validation if it makes no sense (an empty output folder, for example).
Where Defaults Come From: Order of Priority
Larger scripts often accept the same setting from several places. The widely used order, from lowest to highest priority, is:
- Built-in default written in the script.
- Configuration file, such as
~/.config/snapshot.conf. - Environment variable, such as
SNAPSHOT_KEEP. - Command-line option, such as
-k 4.
The idea is that more specific choices win: a configuration file applies to every run, an environment variable to one session or one command, and an option to exactly one run. The simplest way to implement this is to apply the sources in that order, each one overwriting the previous value:
#!/usr/bin/env bash
# precedence: built-in default < environment variable < command-line option
port=${APP_PORT:-8080}
[[ ${1-} == -p ]] && port=$2
echo "port=$port"
$ bash prec.sh
port=8080
$ APP_PORT=9000 bash prec.sh
port=9000
$ APP_PORT=9000 bash prec.sh -p 7000
port=7000
APP_PORT=9000 bash prec.sh sets the variable only for that one command (lesson 36). Whatever order a script chooses, its help text should state it, because the user cannot guess it.
Defaults for Operands
An operand default is usually one line after the parsing loop. Two common cases are "the current folder" and "standard input":
dir=${1:-.}
echo "listing [$dir]"
(( $# )) || set -- -
printf 'operand: [%s]\n' "$@"
$ bash dir.sh
listing [.]
operand: [-]
$ bash dir.sh /etc
listing [/etc]
operand: [/etc]
set -- - replaces the empty list of positional parameters with the single operand -, which many tools (and the wordfreq.sh script of lesson 131) read as standard input. After that line, the rest of the script can loop over "$@" without a special case for "no files".
For a list held in an array, the default is applied when the array is still empty after parsing:
exts=("$@")
(( ${#exts[@]} > 0 )) || exts=(log txt)
printf 'ext: %s\n' "${exts[@]}"
$ bash arr.sh
ext: log
ext: txt
$ bash arr.sh md
ext: md
A user-supplied list replaces the default list entirely instead of being added to it. This is what users normally expect, because otherwise there would be no way to remove log from the list.
Computed Defaults
Some defaults cannot be written as a constant: today's date, the user's cache folder, or a name derived from another argument.
tag=${TAG:-$(date +%Y%m%d)}
cache=${XDG_CACHE_HOME:-$HOME/.cache}/myapp
$ HOME=/home/ana bash xdg.sh
/home/ana/.cache/myapp
$ HOME=/home/ana XDG_CACHE_HOME=/tmp/c bash xdg.sh
/tmp/c/myapp
The default part of an expansion is evaluated only when it is needed. If computing it is slow or has side effects, this matters:
slow_default() { echo "computing default..." >&2; echo "/srv/data"; }
dir=${1:-$(slow_default)}
echo "dir=$dir"
$ bash lazy.sh
computing default...
dir=/srv/data
$ bash lazy.sh /tmp/x
dir=/tmp/x
In the second run, slow_default was never called. A default that depends on another parameter must be computed after that parameter is final. In the complete example below, the snapshot label defaults to the name of the source folder, so it is filled in after the parsing loop, not before.
Keeping the Help Text in Agreement with the Code
If the help says (default: 5) and the code says keep=7, one of them is wrong, and the user will believe the help. The fix is to keep each default in one variable and use it in both places:
readonly DEFAULT_KEEP=7
keep=$DEFAULT_KEEP
echo " -k KEEP copies to keep (default: $DEFAULT_KEEP)"
-k KEEP copies to keep (default: 7)
readonly (lesson 40) prevents the default from being changed by accident later in the script; the working variable keep is a separate, writable copy. Because the help text is a here document with an unquoted delimiter (lesson 131), $DEFAULT_KEEP can be used inside it directly.
Validating Defaults That Come from Outside
A default written in the script is known to be valid. A value from the environment or a configuration file is user input and must be checked exactly like an option value (lesson 128). The simplest approach is to validate the final value after all sources have been applied, whatever its origin:
keep=${SNAP_KEEP:-7}
[[ $keep =~ ^[1-9][0-9]*$ ]] || { echo "envbad.sh: invalid SNAP_KEEP value '$keep'" >&2; exit 2; }
echo "keep=$keep"
$ SNAP_KEEP=ten bash envbad.sh
envbad.sh: invalid SNAP_KEEP value 'ten'
The message names the variable, because the user did not type ten on the command line and would otherwise not know where it came from. The complete example records the origin of every setting so its error messages can do this automatically.
Boolean Defaults and --no- Options
A flag that is on by default needs a way to turn it off. The usual convention is a pair of options, with the last one on the command line winning:
compress=1
for a; do case $a in -z|--compress) compress=1;; --no-compress) compress=0;; esac; done
echo "compress=$compress"
$ bash bool.sh
compress=1
$ bash bool.sh --no-compress
compress=0
$ bash bool.sh --no-compress --compress
compress=1
"Last one wins" also lets a user override a setting that a shell alias or wrapper script adds earlier on the command line.
A Complete Example
snapshot.sh saves a folder as a tar archive and deletes the oldest snapshots beyond a limit. Each setting can come from a built-in default, a configuration file, an environment variable or an option, and --print-config shows the value in effect together with its origin.
#!/usr/bin/env bash
# snapshot.sh - save a compressed tar snapshot of a folder and keep the newest few
set -euo pipefail
prog=${0##*/}
# 1. Built-in defaults: the lowest priority.
readonly DEFAULT_DEST=$HOME/snapshots
readonly DEFAULT_KEEP=5
dest=$DEFAULT_DEST dest_from=default
keep=$DEFAULT_KEEP keep_from=default
compress=yes compress_from=default
label= label_from=default
dry_run=0 print_config=0
usage() {
cat <<USAGE
Usage: $prog [OPTION]... [SOURCE]
Save SOURCE (default: the current folder) as a tar archive in DEST
and delete the oldest snapshots of SOURCE beyond KEEP.
Options:
-d, --dest DIR folder for snapshots (default: $DEFAULT_DEST)
-k, --keep KEEP number of snapshots to keep, 1-99 (default: $DEFAULT_KEEP)
-l, --label NAME file name prefix (default: name of SOURCE)
--no-compress write .tar instead of .tar.gz
-n, --dry-run show what would be done, change nothing
--print-config show the settings in effect and where each came from
-h, --help show this help and exit
Each setting is taken from, in increasing priority: the built-in
default, the config file, the environment, the command line.
Config file: \$SNAPSHOT_CONFIG, or ~/.config/snapshot.conf, with lines
such as dest=~/backups, keep=10, compress=no.
Environment: SNAPSHOT_DEST, SNAPSHOT_KEEP.
USAGE
}
bad_usage() {
printf '%s: %s\n' "$prog" "$*" >&2
printf "Try '%s --help' for more information.\n" "$prog" >&2
exit 2
}
# 2. Config file: overrides the built-in defaults.
config=${SNAPSHOT_CONFIG:-${XDG_CONFIG_HOME:-$HOME/.config}/snapshot.conf}
if [[ -f $config ]]; then
lineno=0
while IFS= read -r line || [[ -n $line ]]; do
lineno=$((lineno + 1))
[[ $line =~ ^[[:space:]]*(#|$) ]] && continue
[[ $line == *=* ]] || bad_usage "$config:$lineno: expected key=value"
key=${line%%=*} value=${line#*=}
value=${value/#\~/$HOME} # allow ~/path in the file
case $key in
dest) dest=$value dest_from="config $config" ;;
keep) keep=$value keep_from="config $config" ;;
compress) compress=$value compress_from="config $config" ;;
*) bad_usage "$config:$lineno: unknown setting '$key'" ;;
esac
done < "$config"
fi
# 3. Environment: overrides the config file. An empty variable counts as unset.
if [[ -n ${SNAPSHOT_DEST-} ]]; then dest=$SNAPSHOT_DEST dest_from="env SNAPSHOT_DEST"; fi
if [[ -n ${SNAPSHOT_KEEP-} ]]; then keep=$SNAPSHOT_KEEP keep_from="env SNAPSHOT_KEEP"; fi
# 4. Command line: the highest priority.
sources=()
while (( $# > 0 )); do
case $1 in
-h|--help) usage; exit 0 ;;
-d|--dest) (( $# > 1 )) || bad_usage "option '$1' requires an argument"
dest=$2 dest_from="option $1"; shift ;;
-k|--keep) (( $# > 1 )) || bad_usage "option '$1' requires an argument"
keep=$2 keep_from="option $1"; shift ;;
-l|--label) (( $# > 1 )) || bad_usage "option '$1' requires an argument"
label=$2 label_from="option $1"; shift ;;
--no-compress) compress=no compress_from="option $1" ;;
-n|--dry-run) dry_run=1 ;;
--print-config) print_config=1 ;;
--) shift; sources+=("$@"); break ;;
-?*) bad_usage "unknown option '$1'" ;;
*) sources+=("$1") ;;
esac
shift
done
(( ${#sources[@]} <= 1 )) || bad_usage "only one SOURCE can be given"
source_dir=${sources[0]:-.}
# Computed default: needs the final SOURCE, so it is filled in last.
[[ -d $source_dir ]] || bad_usage "SOURCE '$source_dir' is not a folder"
source_abs=$(cd -- "$source_dir" && pwd)
if [[ -z $label ]]; then
label=${source_abs##*/}
label=${label:-root}
fi
# Validate the final values, whatever their origin.
[[ $keep =~ ^[1-9][0-9]?$ ]] || bad_usage "KEEP must be 1-99, got '$keep' (from $keep_from)"
[[ $compress == yes || $compress == no ]] \
|| bad_usage "compress must be yes or no, got '$compress' (from $compress_from)"
[[ $label =~ ^[A-Za-z0-9._-]+$ ]] || bad_usage "invalid label '$label' (from $label_from)"
[[ -n $dest ]] || bad_usage "DEST must not be empty (from $dest_from)"
if (( print_config )); then
printf '%-9s %-24s %s\n' source "$source_abs" "" \
dest "$dest" "($dest_from)" keep "$keep" "($keep_from)" \
compress "$compress" "($compress_from)" label "$label" "($label_from)"
exit 0
fi
ext=.tar; tar_z=()
if [[ $compress == yes ]]; then ext=.tar.gz; tar_z=(-z); fi
archive=$dest/$label-$(date +%Y%m%d-%H%M%S)$ext
if (( dry_run )); then
echo "would create $archive"
else
mkdir -p -- "$dest"
tar "${tar_z[@]}" -cf "$archive" -C "${source_abs%/*}/" -- "${source_abs##*/}"
echo "created $archive"
fi
# Keep only the newest KEEP snapshots of this label (names sort by time).
shopt -s nullglob
snaps=("$dest/$label"-[0-9]*-[0-9]*.tar "$dest/$label"-[0-9]*-[0-9]*.tar.gz)
mapfile -t snaps < <(printf '%s\n' "${snaps[@]}" | sort)
(( dry_run )) && exit 0
excess=$(( ${#snaps[@]} - keep ))
for (( i = 0; i < excess; i++ )); do
rm -f -- "${snaps[i]}"
echo "removed ${snaps[i]}"
done
How It Works
- Every setting has a companion
*_fromvariable that records where its current value came from. Each source overwrites both the value and its origin, so after all four steps the origin is always the source that won. - The four sources are applied in priority order: defaults, then the configuration file, then the environment, then the parsing loop. No step needs to know about the others; the last one to set a value wins.
- The configuration file is read, not sourced. Each line is split at the first
=and only the known keys are accepted. Running the file withsourcewould execute any command written in it, which is a security risk (lesson 157). A value that starts with~is expanded by hand with${value/# 0 /$HOME}, because the shell performs tilde expansion only on the command line, not on text read from a file. [[ -n ${SNAPSHOT_DEST-} ]]treats an empty environment variable as unset, and the-inside the braces keepsset -ufrom failing when the variable does not exist at all.- The label default is computed last, from the final SOURCE, which is known only after the parsing loop.
cd -- "$source_dir" && pwdturns a relative path such as.into an absolute one, so its last component is a real folder name. For the root folder/, that component is empty, and the script falls back toroot. - Validation runs once, on the final values, and each message names the origin. A bad value in the configuration file and the same bad value on the command line produce the same check, with a different hint.
--print-configshows the effective settings without doing anything, which is the quickest way for a user to understand the result of the priority rules.- Pruning relies on the time stamp in the file names:
YYYYmmdd-HHMMSSsorts in time order as plain text, so aftersort, the firstexcessentries are the oldest snapshots..tarand.tar.gzfiles are counted together, so switching to--no-compressdoes not leave old compressed copies behind.
Running the Complete Example
The tests ran in /home/ana/project, which contains README and src/app.py, with HOME=/home/ana. With no configuration file and no environment variables, every value is a built-in default except SOURCE:
$ bash snapshot.sh --print-config
source /home/ana/project
dest /home/ana/snapshots (default)
keep 5 (default)
compress yes (default)
label project (default)
A configuration file /home/ana/.config/snapshot.conf changes two settings:
# my snapshot settings
dest=~/backups
keep=3
$ bash snapshot.sh --print-config
source /home/ana/project
dest /home/ana/backups (config /home/ana/.config/snapshot.conf)
keep 3 (config /home/ana/.config/snapshot.conf)
compress yes (default)
label project (default)
An environment variable overrides the file, and options override both:
$ SNAPSHOT_KEEP=2 bash snapshot.sh --print-config
...
keep 2 (env SNAPSHOT_KEEP)
...
$ SNAPSHOT_KEEP=2 bash snapshot.sh -k 4 --no-compress --print-config src
source /home/ana/project/src
dest /home/ana/backups (config /home/ana/.config/snapshot.conf)
keep 4 (option -k)
compress no (option --no-compress)
label src (default)
(The lines marked ... were unchanged from the previous run.) In the last run, the label default followed the new SOURCE, src. An empty SNAPSHOT_DEST= was ignored, and dest still came from the configuration file.
Four real runs, one second apart, with keep=3 from the file:
$ bash snapshot.sh
created /home/ana/backups/project-20261122-105547.tar.gz
$ bash snapshot.sh
created /home/ana/backups/project-20261122-105548.tar.gz
$ bash snapshot.sh
created /home/ana/backups/project-20261122-105549.tar.gz
$ bash snapshot.sh
created /home/ana/backups/project-20261122-105550.tar.gz
removed /home/ana/backups/project-20261122-105547.tar.gz
$ ls ~/backups
project-20261122-105548.tar.gz
project-20261122-105549.tar.gz
project-20261122-105550.tar.gz
Your time stamps will differ. Invalid values are reported with their origin, and the script stops with status 2 before creating anything:
$ SNAPSHOT_KEEP=ten bash snapshot.sh
snapshot.sh: KEEP must be 1-99, got 'ten' (from env SNAPSHOT_KEEP)
Try 'snapshot.sh --help' for more information.
$ bash snapshot.sh -k 0
snapshot.sh: KEEP must be 1-99, got '0' (from option -k)
Try 'snapshot.sh --help' for more information.
$ bash snapshot.sh -l "my app"
snapshot.sh: invalid label 'my app' (from option -l)
Try 'snapshot.sh --help' for more information.
Problems in the configuration file are reported with the file name and line number. These two runs used a file containing keep=3 and colour=blue, and then a file containing compress=maybe:
$ bash snapshot.sh
snapshot.sh: /home/ana/.config/snapshot.conf:2: unknown setting 'colour'
Try 'snapshot.sh --help' for more information.
$ bash snapshot.sh -n
snapshot.sh: compress must be yes or no, got 'maybe' (from config /home/ana/.config/snapshot.conf)
Try 'snapshot.sh --help' for more information.
Finally, the help text prints the defaults from the same variables the code uses, so it shows the real home folder:
$ bash snapshot.sh --help
Usage: snapshot.sh [OPTION]... [SOURCE]
Save SOURCE (default: the current folder) as a tar archive in DEST
and delete the oldest snapshots of SOURCE beyond KEEP.
Options:
-d, --dest DIR folder for snapshots (default: /home/ana/snapshots)
-k, --keep KEEP number of snapshots to keep, 1-99 (default: 5)
-l, --label NAME file name prefix (default: name of SOURCE)
--no-compress write .tar instead of .tar.gz
-n, --dry-run show what would be done, change nothing
--print-config show the settings in effect and where each came from
-h, --help show this help and exit
Each setting is taken from, in increasing priority: the built-in
default, the config file, the environment, the command line.
Config file: $SNAPSHOT_CONFIG, or ~/.config/snapshot.conf, with lines
such as dest=~/backups, keep=10, compress=no.
Environment: SNAPSHOT_DEST, SNAPSHOT_KEEP.
The help shows the built-in defaults, not the values from the configuration file; --print-config is the place to see the values that will actually be used. Lesson 133 continues with the error side of command-line handling: unknown options, typos and invalid values.