Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash scripting: How to ensure script exits on any error in function called with an "or" (||) condition?

Here is an example script:

#!/bin/bash
set -euo pipefail

function_test () {
        echo "Everything still ok."
        thisdoesnotexist
        echo "It continues running..."
}

function_test || { echo "Error occured in function_test."; exit 1; }

I expect this script to exit on "thisdoesnotexist", since set -e is activated. Either the error message "Error occured in function_test." should appear, or at least the script should be exited. What happens instead, is that the script keeps running:

$ ./testscript.sh 
Everything still ok.
./testscript.sh: Zeile 6: thisdoesnotexist: Kommando nicht gefunden.
It continues running...

I figure this is because I'm using the function in an "or" (||) context, according to the manual for set:

Exit immediately [...] unless the command that fails is part of an until or while loop, part of an if statement, part of a && or || list, [...]

What would be the best way to handle this in a script? I have removed the "||" and used an error trap like this:

#!/bin/bash
set -Eeuo pipefail

errorhandler () {
        echo "Errorhandler called. Exiting."
        exit 1
}

trap "errorhandler" ERR

function_test () {
        echo "Everything still ok."
        thisdoesnotexist
        echo "It continues running..."
}

function_test

Which does work:

$ ./testscript.sh 
Everything still ok.
./testscript.sh: Zeile 13: thisdoesnotexist: Kommando nicht gefunden.
Errorhandler called. Exiting.

In this case though it seems impossible to output a user friendly message (which, for example, contains the step in the script, where the error happened). For this I would at least have to pass on the function name to the error trap. I tried that but found no working solution.

Do you have a better suggestion?

like image 702
user40974 Avatar asked Jan 30 '26 22:01

user40974


1 Answers

function_test || { echo "Error occured in function_test."; exit 1; }

The OR never happens because of the functions return status. The last echo statement from the function causes a return status of 0, since it successfully ran.

If you add a non-zero return on the command that isn't successful, then it will cause the OR statement to run properly.

function_test () {
        echo "Everything still ok."
        thisdoesnotexist || return 1;
        echo "It continues running..."
}
like image 78
tDarkCrystal Avatar answered Feb 01 '26 11:02

tDarkCrystal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!