In bash I know that when you use set -e
the script is supposed to "exit immediately if a command exits with a non-zero status." I want to write a script in bash, but I want to modularize my code. So, I am writing everything in functions. I have encountered the following behavior which I find strange
#!/usr/bin/env bash
set -eo pipefail
someFunction() {
local returnVal
echo "failed"
returnVal="$(return 1)"
echo "I got here"
echo "$returnVal"
}
someFunction
echo "I got here"
When I run this script as expected I get:
failed
as my output and it exits out.
However, when I change the function to:
#!/usr/bin/env bash
set -eo pipefail
someFunction() {
local returnVal
echo "failed"
returnVal="$(return 1)"
echo "I got here"
echo "$returnVal"
}
someVal=$(someFunction)
echo "I got here"
echo $someVal
I get the following output
I got here
failed I got here
Not only does it not exit, but it runs everything in the function even after one of the commands fail as I have simulated in this concocted example.
I want to be able to get the return values from the functions, and I want the script to exit out immediately upon any error. It seems like since $()
is running the function in a sub-shell for some reason it is not exiting! Any help would be appreciated it.
I have some functions that have multiple commands that could fail, but I do not want to manually check if the each command failed and return 1 from the function. Is there a way to have bash exit out if an error is encountered? I know if you do the following it exits out
#!/usr/bin/env bash
set -eo pipefail
someFunction() {
local returnVal
echo "failed"
returnVal="$(return 1)"
if [[ $? -ne 0 ]];
then
return 1
fi
echo "I got here"
echo "$returnVal"
}
someVal=$(someFunction)
echo "I got here"
echo $someVal
In this case it would exit out immediately before printing "I got here". I understand that essentially when you write a function in bash you define a new command and when you have echo
at the end it will return 0
and assume the function didn't fail. My functions could have multiple commands, and I do not want to check the return value of each one and then return 1 from my function in order to have it exit!