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

trap ERR for Custom Error Handling

trap ERR lets a script run a custom block of code automatically whenever any command in it fails, similar to a catch block in other languages.

A Basic ERR Trap

trap handler ERR registers code that runs automatically whenever a command in the script fails, in the same situations where set -e would normally stop it.

Example: A Basic ERR Trap

bash
#!/bin/bash
(
    trap 'echo "an error was trapped"' ERR
    set -e
    false
    echo "unreached"
) || echo "subshell exited after the ERR trap ran"

Reporting the Failing Line Number

Inside an ERR trap, $LINENO reflects the line number where the failure occurred, which makes error messages far more useful for pinpointing the actual bug.

Example: Reporting the Failing Line Number

bash
#!/bin/bash
(
    trap 'echo "error occurred near line $LINENO"' ERR
    set -e
    true
    false
) || echo "handled"

Making ERR Traps Work Inside Functions

By default, an ERR trap does not propagate into functions or command substitutions. set -o errtrace (equivalently set -E) extends the trap so it fires no matter where the failure happens.

Example: Making ERR Traps Work Inside Functions

bash
#!/bin/bash
(
    set -E -e
    trap 'echo "caught failure inside a function"' ERR
    fail_inside() {
        false
    }
    fail_inside
    echo "unreached"
) || echo "subshell stopped after the function's failure was trapped"
Common Mistakes
  1. Assuming trap ERR fires for commands exempted from set -e too (like an if condition); it shares the same exemptions.
  2. Forgetting trap ERR only fires reliably when set -e semantics are in effect for that command; behavior can otherwise be inconsistent across contexts like functions unless set -E (errtrace) is also used.
  3. Writing an ERR handler that itself might fail, causing confusing recursive or missed error handling.
Chapter Summary
  • trap handler ERR runs handler whenever a command fails, in the same contexts where set -e would trigger.
  • set -o errtrace (set -E) makes the ERR trap also fire inside functions and subshells, not just top-level commands.
  • An ERR trap is commonly used to log diagnostic information (like the failing line number via $LINENO) before the script exits.
  • Combining trap ERR with an EXIT trap lets you separate error-specific logging from general cleanup that should always run.

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.