Difference between return and exit in Bash functions
From man bash
on return [n]
;
Causes a function to stop executing and return the value specified by n to its caller. If n is omitted, the return status is that of the last command executed in the function body.
... on exit [n]
:
Cause the shell to exit with a status of n. If n is omitted, the exit status is that of the last command executed. A trap on EXIT is executed before the shell terminates.
EDIT:
As per your edit of the question, regarding exit codes, return
has nothing to do with exit codes. Exit codes are intended for applications/scripts, not functions. So in this regard, the only keyword that sets the exit code of the script (the one that can be caught by the calling program using the $?
shell variable) is exit
.
EDIT 2:
My last statement referring exit
is causing some comments. It was made to differentiate return
and exit
for the understanding of the OP, and in fact, at any given point of a program/shell script, exit
is the only way of ending the script with an exit code to the calling process.
Every command executed in the shell produces a local "exit code": it sets the $?
variable to that code, and can be used with if
, &&
and other operators to conditionally execute other commands.
These exit codes (and the value of the $?
variable) are reset by each command execution.
Incidentally, the exit code of the last command executed by the script is used as the exit code of the script itself as seen by the calling process.
Finally, functions, when called, act as shell commands with respect to exit codes. The exit code of the function (within the function) is set by using return
. So when in a function return 0
is run, the function execution terminates, giving an exit code of 0.
return
will cause the current function to go out of scope, while exit
will cause the script to end at the point where it is called. Here is a sample program to help explain this:
#!/bin/bash
retfunc()
{
echo "this is retfunc()"
return 1
}
exitfunc()
{
echo "this is exitfunc()"
exit 1
}
retfunc
echo "We are still here"
exitfunc
echo "We will never see this"
Output
$ ./test.sh
this is retfunc()
We are still here
this is exitfunc()