Why doesn't set -e stop my function when I call it from an if?

November 17, 2026 5 answers
Asked by 6t~zandrel_354

A cleanup function runs a failing command and then prints a success message. With set -e enabled, calling the function as an if condition still reaches the success branch. Why, and how do you handle errors in functions like this?

Answers

3w!nexdrel_417

Bash ignores errexit inside a function when the function itself runs in a context where its status is being tested, such as an if condition. The failed command doesn't stop the function, so a successful echo afterward becomes the function's return status.

For a cleanup function that must stop on failure, make that explicit: use rm "$1/old.log" || return 1 before printing the success message. That makes the function report failure even when it's called from an if.

6b!coppernotch_583:

The caller still needs to decide what failure means. If there's no else branch, the script may continue after the if instead of reporting an overall failure.

Reply to this answer
_r73!zavelo.6

For a function that only needs to run one command, keep that command last and put the success message in the caller's success branch. A function without an explicit return uses the status of its last executed command, so a failing rm will then make the condition fail.

That gets trickier as soon as you add more work after rm. A later successful command can mask the failure again, so this isn't a substitute for checking each required step in a longer function.

Reply to this answer
5k!bracketpickle_374

I prefer explicit checks and useful error messages for operations where failure matters, with set -e at most as a backstop. It takes more typing, but the function can say what failed and return a status the caller can handle. Small helper functions can cut down some of the repetition.

6t~zandrel_354:

That makes sense for cleanup. A partial failure needs a clear message, not just the absence of a success message.

Reply to this answer
f.672~brindlehook

Watch assignments too. In local out=$(some_cmd), the status comes from local, so a failed substitution can be hidden. Declare local out first, then run out=$(some_cmd) separately and check that assignment's status.

Reply to this answer
7f!claywicket_825

Don't assume moving the function call into a different check fixes its internals. Calls used in other tested contexts, including the relevant parts of && and || lists and commands preceded by !, can suppress errexit too.

Running it as a plain statement lets set -e act in the usual case, but then an unhandled failure may exit the shell before you can inspect $?. If the caller needs recovery, make the function propagate failures explicitly and handle its status deliberately.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions