Why Doesn’t My Bash Script Exit with set -e?

0
6
Asked By CuriousCoder42 On

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

Answered By ShellExplorer22 On

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.

Answered By ErrorHandler101 On

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.

Answered By ShellGuru88 On

Thanks for sharing! I wasn't aware of how this works. It clears up a lot.

Answered By DevInsights77 On

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.

Answered By TechSavant99 On

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.

Answered By BashNinja357 On

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.

Answered By CodeWizard1 On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.