The builtin command exit
exits the shell:
exit [n]
Exit the shell, returning a status of n to the shell’s
parent. If n is omitted, the exit status is that of the last command
executed. Any trap on EXIT is executed before the shell terminates.
Running to the end of file also exits, returning the return code of the last command, so yes, a final exit 0
will force the script to exit with successful status. The exit codes of any earlier commands don't matter. (At the end of a script you could also use true
or :
to get an exit code of zero.) Of course more often you'd use exit
from inside an if
to end the script in the middle.
These should print a 1 ($?
contains the exit code returned by the previous command):
sh -c "false" ; echo $?
sh -c "false; exit" ; echo $?
While this should print a 0:
sh -c "false; exit 0" ; echo $?
I'm not sure if the concept of the script "failing" when executing an exit
makes sense, as it's quite possible to some commands ran by the script to fail, but the script itself to succeed. It's up to the author of the script to decide what is a success and what isn't.
Oh, and, exit codes are 8 bits wide, so the range is 0..255. Codes above 127 are used when a process is terminated by a signal, but they can be returned in the usual way. The wait
system call actually a value with a larger range, the rest contains basically status bits set by the kernel.
exit 0
, it will exit with the exit code of 0 regardless of what happens within the script. – Hatclock Sep 6 '16 at 14:26exit 0
, it will exit with the code 0 only if that last instruction was executed. The only impact ofexit 0
at the end of the script is to return 0 instead of the status from the previous instruction. – Gilles Sep 6 '16 at 22:08