Linux Basic — Handling Errors

1 minute read

Handling Errors

By default, Bash scripts march on after errors. A failed cp, an unset variable, a broken pipe — none of these stop execution. That’s the right default for an interactive shell, but it’s terrifying in scripts that touch real systems.

This chapter is about flipping that default. The same techniques that make Python or Go crash-on-error make Bash trustworthy.


What You Will Learn

By the end of this chapter you will be able to:

  • Read and return exit codes correctly
  • Enable strict mode with set -euo pipefail and know what each flag does
  • Catch and report errors with trap … ERR and trap … EXIT
  • Write reusable die, warn, and info helpers
  • Recognise when strict mode bites — and how to opt out for one command

Topics in This Chapter

# Topic Description
1 Exit Codes $?, conventions, exit N
2 set -e and set -u fail on errors, fail on unset vars
3 set -o pipefail catch errors in the middle of a pipe
4 trap Command run code on EXIT, ERR, signals
5 Custom Error Functions die, warn, require
6 Practice Exercises Hands-on tasks

The Three-Line Strict-Mode Header

Almost every production Bash script should start with:

#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'

What that gives you:

  • -e — exit immediately if any command fails (with caveats — page 2)
  • -u — error on unset variables
  • -o pipefail — a failing command anywhere in a pipe fails the whole pipe
  • IFS=$'\n\t' — word-split only on newline/tab, not space (saves you from a thousand quoting bugs)

We’ll dissect each in detail. Used together, they turn Bash into a fail-fast language.


Next → Exit Codes

Updated: