brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ${var:?} stops a script before an empty variable eats your files

Shell
~/tips/tip-shell-parameter-guard-rm

rm -rf "${BUILD_DIR:?BUILD_DIR is not set}"/*

Stops the script with an error when a variable is empty, before a delete can hit the wrong path.

rm -rf "$dir"/* is fine until $dir is empty. Then it is rm -rf /*. I would rather not find out how well the safety nets work.

Bash has a parameter expansion for this. ${var:?message} checks the variable. If it is unset or empty, the shell prints the message to stderr and a non-interactive shell exits. No command runs.

#!/usr/bin/env bash
rm -rf "${BUILD_DIR:?BUILD_DIR is not set}"/*

With BUILD_DIR empty you get line 2: BUILD_DIR: BUILD_DIR is not set and the script stops. Without the message, Bash uses a default text such as “parameter null or not set”. There is also ${var:-default} if you would rather fall back to a value than stop.

The caveat: with the colon it triggers on empty as well as unset. Leave the colon out, ${var?msg}, and only a truly unset variable fails. And in an interactive shell it prints the error but does not close your terminal, so it is a script habit.

If you would rather not trust yourself at all, set -u at the top makes any unset variable a hard error. The guard is still worth writing out, because it tells the next reader what you were afraid of.

Further reading: Bash manual: Shell Parameter Expansion, On this site: trap EXIT cleans up your temp files, even when the script dies, On this site: set -o pipefail makes a pipeline fail when any part of it fails

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link