Interview Prep/Shell Scripting/Troubleshooting: tools, portability, permissions and environment

A cleanup logged `cd: /srv/app/current/cache: No such file or directory` and then deleted the contents of the deploy user's home directory. The code was `cd $CACHE_DIR; rm -rf *`.

BeginnerTroubleshootingTroubleshooting: tools, portability, permissions and environment
Answer

Likely causes → The cd failed (directory missing after a release switch, or CACHE_DIR empty, making cd go to $HOME), the script did not stop, and rm -rf * ran in whatever the current directory was.

Diagnose → The log line order shows cd failing immediately before the deletions; shellcheck reports SC2164 ("Use cd ... || exit in case cd fails").

Fix → Never combine a relative wildcard delete with an unchecked cd. Delete by absolute path with guards:

: "${CACHE_DIR:?CACHE_DIR not set}"
[[ -d $CACHE_DIR && $CACHE_DIR == /srv/app/* ]] || die "refusing to clean '$CACHE_DIR'"
find "$CACHE_DIR" -mindepth 1 -delete
# or: cd -- "$CACHE_DIR" || exit 1

Prevent → set -e plus ShellCheck in CI, ${var:?} on every path used in a delete, and an allow-list prefix check before destructive operations.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: tools, portability, permissions and environment