Interview Prep/Shell Scripting/Troubleshooting: strict mode, exit codes, pipelines and traps

Temp directories pile up in `/tmp` even though the script has `trap "rm -rf $workdir" EXIT`.

BeginnerTroubleshootingTroubleshooting: strict mode, exit codes, pipelines and traps
Answer

Likely causes → Double quotes expand $workdir when the trap is set, not when it fires. The trap was set before workdir=$(mktemp -d), so it holds rm -rf with an empty path and deletes nothing. (If workdir had an old value, it would delete the wrong thing.)

Diagnose →

trap -p EXIT        # shows: trap -- 'rm -rf ' EXIT

Fix → Single-quote the trap so the variable expands at exit time, and guard against an empty value:

workdir=$(mktemp -d)
trap 'rm -rf -- "${workdir:?}"' EXIT

Prevent → Always single-quote trap bodies, or call a cleanup function. ShellCheck SC2064 flags double-quoted traps.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: strict mode, exit codes, pipelines and traps