Bash Scripting — Handling Errors in Bash Scripts

1 minute read

Introduction

Welcome to Chapter 23 — Handling Errors in Bash Scripts! 🛡️

If you’ve ever had a script silently fail halfway through — deleting wrong files, writing garbage data, or just… stopping with no explanation — this chapter is your fix.

Error handling is what separates a quick hack from a production-ready script. By the end of this chapter, you’ll know exactly how to make your scripts fail loudly, fail early, and clean up after themselves.


What You’ll Learn

This chapter covers five core topics:

# Topic What You’ll Master
1 Exit Codes $?, exit N, conventional codes (0, 1, 2, 126, 127, 128+N)
2 set -e and set -u Auto-exit on failure, catch unset variables
3 set -o pipefail Detect failures hidden inside pipelines
4 trap Command Cleanup on exit, catch signals, debug with ERR traps
5 Custom Error Functions die(), colored logging, production-grade error templates

After the lessons, put it all together with the Practice Exercises.


Why Error Handling Matters

Consider this innocent-looking script:

#!/usr/bin/env bash

cd /tmp/build
rm -rf *

What happens if /tmp/build doesn’t exist? The cd fails silently, and rm -rf * runs in whatever directory you’re currently in. That’s catastrophic.

With proper error handling:

#!/usr/bin/env bash
set -euo pipefail

cd /tmp/build
rm -rf *

Now the script stops immediately if cd fails. Crisis averted.


The Golden Rule

Every script you write from this chapter forward should start with:

#!/usr/bin/env bash
set -euo pipefail

This single line gives you:

  • -e → Exit immediately if any command fails
  • -u → Treat unset variables as errors
  • -o pipefail → Catch failures inside pipelines

We’ll break down each of these in detail in the upcoming lessons.


Prerequisites

Before diving in, you should be comfortable with:

  • Basic Bash syntax (variables, conditionals, loops)
  • Running scripts from the terminal
  • Pipes and redirection (|, >, 2>&1)

If you need a refresher, revisit the earlier chapters first — no shame in that! Solid fundamentals make error handling much easier to grasp.


How to Use This Chapter

  1. Read each lesson in order — they build on each other
  2. Type out every example — don’t just read, run the code
  3. Break things on purpose — remove set -e, use wrong paths, see what happens
  4. Finish with the exercises — they tie everything together

Let’s make your scripts bulletproof. Start with Exit Codes →

Updated: