Why is `rm -rf "$DIR/"*` dangerous, and how do you guard deletions?
IntermediateConceptShellCheck, debugging, testing, portability and security
Answer
If DIR is unset or empty (a typo, a failed command), the line becomes rm -rf /*. The famous Steam-for-Linux bug did exactly this with rm -rf "$STEAMROOT/"*.
set -u
rm -rf -- "${DIR:?DIR is empty}/"*
[[ $DIR == /srv/app/releases/* ]] || die "refusing to delete outside releases: $DIR"
Guard with ${VAR:?}, check the path against an expected prefix, and prefer find "$DIR" -mindepth 1 -delete with a validated DIR.
More on ShellCheck, debugging, testing, portability and security
What is ShellCheck and how do you use it in a team?BeginnerHow do you disable a ShellCheck warning, and when is that acceptable?IntermediateName the ShellCheck warnings you see most and what each means.IntermediateHow do you debug a Bash script?BeginnerHow do you make `set -x` output more useful with `PS4`?IntermediateWhat is bats, and how do you test a script that calls external commands?Intermediate