Reliable scripts anticipate failure: check exit codes, use traps, and fail pipelines predictably. CI jobs depend on correct non-zero exits.
set -e and pipefail
set -euo pipefail
false
echo "never runs"With -e, the script stops at false unless you handle it.
trap cleanup
cleanup() { echo "removing temp"; rm -f /tmp/demo.$$; }
trap cleanup EXIT
echo "working..."
# script ends -> trap runsEXIT trap runs on normal exit and many failures—good for temp files.
Conditional failure
if ! cp missing.txt dest.txt 2>/dev/null; then
echo "copy failed, using default" >&2
fiif ! cmd tests failure without tripping set -e in an if list.
Important interview questions and answers
- Q: What does pipefail do?
A: Pipeline returns failure if any stage fails, not only the last. - Q: trap EXIT use?
A: Run cleanup (temp files, echo status) when shell exits.
Self-check
- Which set option catches unset variables?
- Why use if ! cmd instead of cmd alone under set -e?
Tip: Pair trap cleanup with mktemp for safe temp files.
Interview prep
- trap EXIT?
Run cleanup when shell exits.
- if ! cmd?
Test failure without triggering set -e exit.