TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
ERR trap in Bash is an event-driven exception handling mechanism that executes a specified command or function whenever a command, pipeline, list, or arithmetic evaluation terminates with a non-zero exit status. It intercepts failures synchronously at the point of execution, temporarily suspending the script’s normal flow to evaluate the trap payload.
Syntax
Execution Mechanics
When a command yields a non-zero exit status, Bash evaluates theERR trap payload in the current shell environment. Once the trap completes, script execution resumes at the command immediately following the one that failed, unless the trap explicitly invokes exit or the shell is operating under set -e (errexit). If set -e is enabled, the ERR trap executes immediately before the shell terminates.
Contextual Variables
During the execution of anERR trap, Bash populates specific environment variables that provide context about the failure:
$?: Contains the integer exit status (1-255) of the command that triggered the trap.$BASH_COMMAND: Contains the literal string of the command that failed, exactly as it was evaluated by the shell.$LINENO: Contains the script line number where the failing command was executed.
Scope and Inheritance (errtrace)
By default, ERR traps are strictly bound to the execution environment in which they are declared. They are not inherited by shell functions, command substitutions, or subshells.
To force the ERR trap to propagate down the call stack into sub-environments, you must enable the errtrace option:
Trigger Exceptions
TheERR trap adheres to the exact same suppression rules as the set -e (errexit) option. The trap will not trigger if the failing command is part of a conditional test or a boolean chain where the failure is considered handled by the shell’s logic.
Specifically, the ERR trap is suppressed when the failing command is:
- Part of the condition in an
iforelifstatement. - Part of the condition in a
whileoruntilloop. - Part of a boolean list connected by
&&or||, except for the final command in the chain. - Negated using the
!operator (e.g.,! false). - Any command in a pipeline other than the last command, unless
set -o pipefailis enabled.
Master Bash with Deep Grasping Methodology!Learn More





