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).
return
is that for functions defined likef() (...; cmd; return)
, it prevents the optimisation that a few shells do of running thecmd
in the same process as the subshell. With many shells, that also means that the exit status of the function doesn't carry the information thatcmd
has been killed when it has (most shells can't retrieve that information anyway). – Stéphane Chazelas May 28 '18 at 12:43sh
orposh
), you'd needreturn -- "$?"
if there was a chance that the last command was a function that returned a negative number.mksh
(also based on pdksh) forbids functions from returning negative values. – Stéphane Chazelas May 28 '18 at 16:55return x
functions differently thanexit x
...the only thing I do know is thatreturn x
will not exit the current process. – Alexander Mills May 28 '18 at 17:51return
is used to return from a function or a dot script.exit
does something completely different (terminates a process). – Kusalananda May 28 '18 at 17:53