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 commandexecuted in the function body. If used outside a function, butduring execution of a script by the . (source) command, itcauses the shell to stop executing that script and return eithern or the exit status of the last command executed within thescript as the exit status of the script. If used outside afunction and not during execution of a script by ., the returnstatus is false. Any command associated with the RETURN trap isexecuted 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 statusis 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 -efunction test {exit 10}test || echo "ok"echo "I'm here"
Output:
#!/bin/bashset -efunction test {exit 10}test || echo "ok"echo "I'm here"
Output:
#!/bin/bash# set -efunction test {return 10}test || echo "ok"echo "I'm here"
Output: ok I’m here
#!/bin/bashset -efunction test {return 10}test || echo "ok"echo "I'm here"
Output:
ok
I’m here
#!/bin/bashset -efunction test {return 10}testecho "I'm here"
Output:
#!/bin/bash# set -efunction test {return 10}testecho "I'm here"
Output: I’m here
