How to use traps and error-handling options in Bash
How to use traps and error-handling options in Bash
https://www.howtogeek.com/bash-error-handling-patterns-i-use-in-every-script/
Publish Date: 2026-01-31 06:30:00
Source Domain: www.howtogeek.com
Are you learning Bash or wishing to improve error handling in your scripts? The rules governing errors can be a little tricky to understand, so I’ve put together this bite-sized guide to untangle their mystery.
Related
3 good reasons to replace Bash with Zsh
Zsh is more advanced than Bash and has much more potential to boost your terminal throughput.
The initial pattern I learned—and often the first recommended—is the set -e option. It simply makes your script exit when it detects a non-zero exit code. For those unaware, an exit code is a number returned by all programs on Linux, and when it’s non-zero, it’s an error. You can see the exit code of the most recently exited process with echo $?.
Let’s look at a few examples.
When everything is okay:
#!/usr/bin/env bash
ls /
echo Exit code: $?
…
Source