Interview Prep/Shell Scripting/ShellCheck, debugging, testing, portability and security

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on ShellCheck, debugging, testing, portability and security