Bash – Implicit return in bash functions

bashbash-functionsshell-script

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). If return 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,

gmx () {
  echo 'foo'
  return "$?"
}

is therefore equivalent to

gmx () {
  echo 'foo'
  return
}

which is the same as

gmx () {
  echo 'foo'
}

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).