Say I have a bash function like so:
gmx(){
echo "foo";
}
will this function implicitly return the exit value of the echo
command, or is using return necessary?
gmx(){
echo "foo";
return $?
}
I assume that the way bash works, the exit status of the final command of the bash function is the one that gets "returned", but not 100% certain.
Best Answer
return
does an explicit return from a shell function or "dot script" (a sourced script). Ifreturn
is not executed, an implicit return is made at the end of the shell function or dot script.If
return
is executed without a parameter, it is equivalent of returning the exit status of the most recently executed command.That is how
return
works in all POSIX shells.For example,
is therefore equivalent to
which is the same as
In general, it is very seldom that you need to use
$?
at all. It is really only needed if you need to save it for future use, for example if you need to investigate its value multiple times (in which case you would assign its value to a variable and perform a series of tests on that variable).