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?