What it does
Every command returns an exit status: 0 means success, any other number an error. $? holds the status of the last command. Scripts should end with exit 0 on success and a non-zero code for errors, so that other scripts, cron and systemd know what happened. exit in an interactive shell logs you out.
How to write it
exit [N]
return [N]Main parts
0- Success.
1- General error.
2- Wrong use (often from builtins).
126- Found, but cannot run.
127- Command not found.
128+N- Killed by signal N (130 = Ctrl+C, 137 = kill -9).
Options 1
Most used
Nothing matches this filter.
Examples 10
$ run as a normal user# run as root (or with sudo)
1End a script with success
tail -1 backup.sh exit 0The caller sees 0.
2Exit with an error
Message to stderr, code 1.
3See the status of the last command
ls uses 2 for this error.
4Command not found
nosuchcommand; echo $? 127127 = not found.
5Killed by Ctrl+C
128 + 2 (SIGINT).
6Return from a function
return = exit for functions.
7Use the status in if
if checks the exit status.
8Pass on the status of the last command
cp a b; exitexit without N uses the status of cp.
9Leave a root shell
exitBack to your own user.
10Exit codes in systemd
status=203/EXEC = the program could not be run.
Nothing matches this filter.
Exit codes
N :: The given value (or the last command's status).