I recently stumbled upon a peculiar behavior in Bash when it comes to error handling while experimenting with the `set -e` option. In my script, I expected it to exit if the `build_project` function fails, given that I've set `set -e`. Here's what I have:
```bash
set -e
echo "Starting deployment..."
build_project && deploy_project
echo "Deployment complete"
```
However, the output shows "Deployment complete" even if `build_project` fails. As I understand it, `set -e` does not trigger an exit if a failing command is part of a conditional context like `&&`, `||`, or within an `if` statement. So when `build_project` fails:
- The failure happens, but because it's part of an `&&` context, Bash allows the script to continue.
I've been delving into these edge cases lately, especially for interviews, and have a more detailed breakdown to share if anyone's interested.
7 Answers
What you're looking for might be `set -eo pipefail`, but keep in mind that's useful for pipelines, and you aren't using them here.
That's right! `set -e` will only exit on untested errors, as noted in the manual. It specifically states that it will not exit for commands in `&&` or `||` lists.
Thanks for sharing! I wasn't aware of how this works. It clears up a lot.
In general, I lean towards writing my own error handling instead of relying on `set -e`, especially in more complex scripts. While it might seem okay in simple cases, as your script grows, you really want to manage errors and clean up properly instead of just exiting at the first failure.
You should include a `||` statement to handle failures yourself. The `set -e` only applies to the last command in a command list. As outlined in the Bash manual, it won't exit if the command that fails is part of an `&&` or `||` list, except for the final command in the chain.
According to POSIX, if any command in a multi-command pipeline fails, it won't cause the shell to exit. Only if the entire pipeline fails will it result in an exit.
You're spot on! When using constructs like `if`, `&&`, or `||`, these are called tested commands, and `set -e` doesn’t apply to them. It only triggers on untested failures.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically