Issue
I have the following script:
#!/usr/bin/env bash
set -Eeuo pipefail
func() {
false
echo "Should not be here"
}
if func; then
echo "Test passed"
else
echo "Test not passed"
fi
I want it to fail on the false
statement and stop the execution of the function. But despite the -e
option, the function doesn't stop when it's in the if
statement. The result of this script is:
Should not be here
Test passed
I tried to use a subshell ( set -e ... )
but it doesn't have an effect, the function is still executed until the end.
How to stop the function execution on an error in the if
statement?
Update: I need the -e
option to be kept so that (func); if []
variant is not an option.
Update 2: There are many commands in my real function and I don't want to make a mess checking the return value of each and every command. Just stop the execution on error in any of the commands. I've simplified the example just to demonstrate what I need.
PS: Changed the function name to not mess things.
Solution
I ended up with the following approach that doesn't mess my code with checking each and every line:
set -e
...
func() {(
set -e
...
command that fails
echo "Should not be here"
)}
set +e
func; r=$?
set -e
if [ $r = 0 ]; then
echo "Test passed"
else
echo "Test not passed"
fi
This works as expected and only prints Test not passed
. I can add any number of lines in the func
and failure of any of them will break the whole function execution. And the whole script has the -e
option set. Everything as I need with minimal code additions.
Answered By - Alexander Pravdin Answer Checked By - Candace Johnson (WPSolving Volunteer)