What is the difference between the return
and exit
statement in Bash functions 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.
Answer: exit() is a system call which terminates current process. exit() is not an instruction of C language. Whereas, return() is a C language instruction/statement and it returns from the current function (i.e. provides exit status to calling function and provides control back to the calling function).
You can also use the “exit” clause to exit the bash script while stating 1 with it at run time. So, open the same file and update your code as we have done before. The only change is “exit 1” instead of “exit” or “exit 0”. Save your code and quit the editor via “Ctrl+S” and “Ctrl+X”.
The exit status is an integer number. For the bash shell's purposes, a command which exits with a zero (0) exit status has succeeded. A non-zero (1-255) exit status indicates failure. If a command is not found, the child process created to execute it returns a status of 127.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With