function() {
if something_that_will_fail; then
irrelevantcode
else
echo "should be here"
false
fi
}
echo $function
This outputs "should be here". How do I get the false value?
You seem to be confusing the output with returned value.
$function is a variable, you don't seem to populate it anywhere. To populate it with the output of the function, use
output=$(function_call)
The return value of a function can be retrieved from the special variable $?.
function_call
value=$?
If you want to use it in a condition, you often don't need the variable at all, as you can run the function directly in the condition:
function_call
if (( $? )) ; then
echo There was an error
else
echo Everything OK
fi
can be shortened to
if function_call ; then
echo Everything OK
else
echo There was an error
fi
Bash has no built-in boolean variables. Further, calling a function a la $function_name also seems wrong to me.
I am not sure, what you are trying to achieve, but you have two options there:
return key (this is what return is all about); here you can also specify a status code within a range 0-255 for your return, where 0 indicates that function terminated successfully, and all other numbers indicate the opposite. Example:
#!/usr/bin/env bash
function is_greater() {
local value1=$1
local value2=$2
if [[ $value1 -gt $value2 ]]; then
printf "%s is greater than %s! \n" $value1 $value2
return 0
else
printf "%s is NOT greater than %s! \n" $value1 $value2
return 1
fi
}
what_func_says=$(is_greater 21 42)
func_exit_status=$?
if [[ $func_exit_status -eq 0 ]]; then
echo $what_func_says
printf "success code: %s \n" $func_exit_status
else
echo $what_func_says
printf "error code: %s \n" $func_exit_status
fi
Output:
21 is NOT greater than 42!
error code: 1
falseis a command that always has an exit status of 1, not a value.false, so the function will exit with a status of 1 (indicating failure), but if the function does anything after thefalsecommand, that status will change. That's why it's better to use something likereturn 1to control the function's exit status;return, by definition, is the last thing the function will execute, so it has complete control over the exit status.