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?
Why doesn't set -e stop my function when I call it from an if?
Answers
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.
Reply to this answer
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
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
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
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.
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.