>DevOps Interview KB

A deployment script creates a temporary lock file at the start, but if the script fails partway through, the lock file is left behind and blocks every future run. How would you fix this?

IntermediatePracticalBash6 min read

Short Answer

Use trap to register a cleanup function that runs automatically on script exit, regardless of whether the script finished normally, failed, or was interrupted — trap 'rm -f "$LOCKFILE"' EXIT guarantees the lock file gets removed no matter how the script actually terminates, rather than relying on cleanup code at the end of the script that only runs if execution reaches that point normally.

Detailed Explanation

The core problem is that cleanup code placed at the end of a script only executes if the script actually reaches that line — any failure, early exit, or interruption before that point (exactly the cases where cleanup matters most, since something went wrong) skips right past it, leaving the cleanup undone. trap solves this by registering a handler that Bash guarantees to run when the script exits, regardless of the exit path.

trap 'commands' EXIT runs on any script termination: whether the script finishes normally, calls exit explicitly, fails due to set -e, or is terminated by certain signals, the EXIT trap fires — this is fundamentally different from cleanup code at the end of the script, which is just another line that has to be reached through normal execution flow to run at all.

LOCKFILE="/tmp/deploy.lock"
trap 'rm -f "$LOCKFILE"' EXIT

Interview Follow-Up Questions

  • How would you handle a case where the cleanup itself might fail — should the script still report the original error, or the cleanup failure?
  • What's the difference between trapping `EXIT` versus trapping specific signals like `INT` and `TERM`, and when would you need both?
  • How would you test that your trap-based cleanup actually works correctly across different failure scenarios, not just the happy path?

Key Takeaways

  • Cleanup code placed at the end of a script only runs if execution reaches that line normally — exactly the cases where cleanup matters most (a failure or interruption) skip right past it.
  • trap 'cleanup-command' EXIT guarantees the cleanup runs regardless of how the script actually terminates, closing this gap structurally rather than relying on normal control flow reaching the end.
  • Register the trap immediately after creating the resource needing cleanup, so no window exists where the resource could leak before cleanup is guaranteed.
  • The same pattern applies to any resource needing guaranteed cleanup — temp files, background processes, lock files, partial transactions — not just this specific lock-file example.

References

Last updated August 22, 2026 · Last reviewed August 22, 2026