Skip to content
Learn Netverks

Lesson

Step 23/36 64% through track

error-handling-bash

Error handling

Last reviewed May 28, 2026 Content v20260528
Track mode
none
Means
Read / quiz
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Error handling: the syntax, patterns, and safety habits you need before advancing in Bash.

Teams still ship Error handling in Bash codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Error handling in contexts like: CI jobs, server maintenance, local dev automation, and Git hooks.

Read each lesson, copy bash examples into your own terminal, and complete the lesson MCQs—there is no in-browser runner for security reasons.

When you can explain the previous lesson's ideas without copying starter code.

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 runs

EXIT 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
fi

if ! cmd tests failure without tripping set -e in an if list.

Important interview questions and answers

  1. Q: What does pipefail do?
    A: Pipeline returns failure if any stage fails, not only the last.
  2. Q: trap EXIT use?
    A: Run cleanup (temp files, echo status) when shell exits.

Self-check

  1. Which set option catches unset variables?
  2. 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.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • trap EXIT?
  • errexit in CI?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump