How do you make a Bash script fail fast and clean up with trap?
Assesses fundamental understanding of Shell & Bash conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
Robust scripts fail fast and release resources.
#!/usr/bin/env bash
set -euo pipefail
cleanup() { rm -f "$tmp"; echo "cleaned" >&2; }
tmp=$(mktemp)
trap cleanup EXIT ERR INT TERM
false || echo "handled"
set -eexits when a command fails, but not insideif,while,||or&&conditions.set -uerrors on unset variables; use${var:-default}for optional values.set -o pipefailmakes a pipeline fail if any stage fails, not only the last.trap 'cmd' EXITalways runs on exit,ERRfires on error, andINTorTERMhandle signals.trap -plists active traps.
Pitfalls: set -e is skipped in some subshell and function contexts, so check critical commands explicitly, and remember traps are reset in subshells. Always quote variables and prefer [[ ]] in bash.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.