In a bash function, we have two ways to terminate the function : return
and exit
return
:
$ help return return: return [n] Return from a shell function. Causes a function or sourced script to exit with the return value specified by N. If N is omitted, the return status is that of the last command executed within the function or script.
Exit Status:
Returns N, or failure if the shell is not executing a function or script.
Here is another explaination:
return [n]
Causes a function to exit with the return value specified by n.
If n is omitted, the return status is that of the last command
executed in the function body. If used outside a function, but
during execution of a script by the . (source) command, it
causes the shell to stop executing that script and return either
n or the exit status of the last command executed within the
script as the exit status of the script. If used outside a
function and not during execution of a script by ., the return
status is false. Any command associated with the RETURN trap is
executed before execution resumes after the function or script.
The return value is stored into $?
in the context of the running script. When set -e
is set at the begining of the script, script will stop at the line where the excuted command returns non-zero status, and this status code is further set into the $?
outside of the script —- the context of the parent script or the shell.
exit
:
$ help exit exit: exit [n]
Exit the shell.
Exits the shell with a status of N. If N is omitted, the exit status
is that of the last command executed.
always cause normal process termination.
A script will stop running whenever it sees exit, and the exit code is returned and set into $?
of its parent or caller context (outside of the script). If exit code is missing, the exit status is that of the last command excuted.
Examples:
#!/bin/bash
# set -e
function test {
exit 10
}
test || echo "ok"
echo "I'm here"
Output:
#!/bin/bash
set -e
function test {
exit 10
}
test || echo "ok"
echo "I'm here"
Output:
#!/bin/bash
# set -e
function test {
return 10
}
test || echo "ok"
echo "I'm here"
Output: ok I’m here
#!/bin/bash
set -e
function test {
return 10
}
test || echo "ok"
echo "I'm here"
Output:
ok
I’m here
#!/bin/bash
set -e
function test {
return 10
}
test
echo "I'm here"
Output:
#!/bin/bash
# set -e
function test {
return 10
}
test
echo "I'm here"
Output: I’m here