Bash Error Handling: How to Use set -o errtrace for Reliable Scripts
admin
#Bash Error Hling: How Use set -o errtrace for Reliable Scripts
Understanding set -o errtrace
in Bash: Error Handling in Functions and Subshells
When writing reliable and maintainable Bash scripts, especially for automation and DevOps tasks, handling errors effectively is crucial. One underused but powerful Bash option is set -o errtrace
, or its shorthand set -E
.
In this article, we’ll explore what errtrace
does, why it's important, and how to use it to make your shell scripts more robust.
trap ERR
Doesn't Work in Functions by DefaultYou may know that you can trap errors using:
trap 'echo "An error occurred!"' ERR
But did you know that this trap does not work inside functions or subshells by default?
trap 'echo "Something went wrong!"' ERR
failing_function() {
false # This command fails
}
failing_function
Expected Output:
Something went wrong!
Actual Output:
(No output — the trap is ignored in the function)
set -o errtrace
or set -E
To inherit the ERR
trap into functions and subshells, use:
set -o errtrace
# or the shorthand:
set -E
set -E
trap 'echo "Something went wrong!"' ERR
failing_function() {
false
}
failing_function
Output:
Something went wrong!
Now the trap works even inside the function!
To write safe and predictable scripts, combine the following:
set -eEuo pipefail
trap 'echo "Error occurred at line $LINENO"' ERR
set -e
: Exit script on any error
set -u
: Treat unset variables as errors
set -o pipefail
: Catch errors in piped commands
set -E
: Inherit ERR
traps in functions/subshells
Imagine you’re writing a deployment script:
set -eEuo pipefail
trap 'echo "Deployment failed at line $LINENO"' ERR
deploy() {
echo "Starting deployment..."
false # Simulating a failure
echo "Deployment finished"
}
deploy
Without set -E
, the trap wouldn’t run. With it, the error is properly logged and caught.
Using set -o errtrace
(or set -E
) in your Bash scripts ensures consistent error trapping behavior across functions and subshells. This small addition can make your scripts much more reliable, especially in production or automation pipelines.
🔧 Tip: Always test your trap and error handling logic — one small flag can change everything!