← Back to Bash Course | Chapter 12: Error Handling & Debugging | Lesson 3 of 12

Error Handling

In this page:

  1. Error Handling

Error Handling

Beyond set -e, scripts should explicitly check the exit status of critical commands (via $? or directly in an if) and respond appropriately, such as printing a message and exiting. Wrapping risky sections and checking results makes failure modes intentional rather than accidental. Good error handling makes a script fail loudly and clearly instead of silently producing wrong results.

Note: Print error messages to stderr with >&2 so they don't get mixed into a script's normal output stream.

Example: Error Handling

bash
#!/bin/bash
run_task() {
    false  # simulate a failing command
}

(
    if run_task; then
        echo "Task succeeded"
    else
        echo "Error: task failed" >&2
        exit 1
    fi
)
echo "Subshell exited with status $?, script continues"

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.