How do you write a safe temporary file or directory in bash?
⚡
Quick Answer
Use mktemp and clean up with a trap on EXIT.
Detailed Answer
Hard-coded /tmp/foo is a race and a security risk. mktemp creates a uniquely named file/dir with safe permissions; register a trap 'rm -rf "$tmp"' EXIT so it's removed even if the script exits early. This avoids leaks and predictable-name attacks.
Code Example
tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT
💡
Interview Tip
Pair mktemp with a trap EXIT cleanup.
bashmktemptrap