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

Error Handling

Error handling is like checking that a cake really came out of the oven fine before serving it. Your script looks at whether each important step worked and reacts with a helpful message.

In this page:

  1. Error Handling
Syntax
bash
if ! command; then
  echo "error message" >&2
  exit 1
fi

command || handle_error

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"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Ignoring exit codes, so the script keeps going after a failure.
  2. Printing errors to standard output rather than >&2.
  3. Using exit with the wrong number, since 0 means success.

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.