Exit and Exit Status

The exit command terminates a script, just as in a C program. It can also return a value, which is available to the script’s parent process.

Every command returns an exit status (sometimes referred to as a return status or exit code). A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code. Well-behaved UNIX commands, programs, and utilities return a 0 exit code upon successful completion, though there are some exceptions.
Likewise, functions within a script and the script itself return an exit status. The last command executed in the function or script determines the exit status. Within a script, an exit nnn command may be used to deliver an nnn exit status to the shell (nnn must be an integer in the 0 – 255 range).

[root@server ~]# ls -l
total 12
-rw-r–r– 1 root root 0 Aug 10 16:54 [6556],
-rw-r–r– 1 root root 0 Aug 10 16:54 accept,
-rw——-. 1 root root 1178 Aug 9 20:55 anaconda-ks.cfg
-rwxr-xr-x 1 root root 6945 Aug 10 15:29 boot.sh
-rw-r–r– 1 root root 0 Aug 10 16:54 tcp,

[root@server ~]# touch /root/test

[root@server ~]# echo $?
0

[root@server ~]# ls -l
total 12
-rw-r–r– 1 root root 0 Aug 10 16:54 [6556],
-rw-r–r– 1 root root 0 Aug 10 16:54 accept,
-rw——-. 1 root root 1178 Aug 9 20:55 anaconda-ks.cfg
-rwxr-xr-x 1 root root 6945 Aug 10 15:29 boot.sh
-rw-r–r– 1 root root 0 Aug 10 16:54 tcp,
-rw-r–r– 1 root root 0 Aug 14 10:19 test

[root@server ~]# cat /root/one
cat: /root/one: No such file or directory

[root@server ~]# echo $?
1

[root@server ~]# ls one
ls: cannot access one: No such file or directory
[root@server ~]# echo $?
2

The exit command in bash accepts integers from 0 – 255, in most cases 0 and 1 will suffice however there are other reserved exit codes that can be used for more specific errors.

Exit Code Number Meaning
1 Catchall for general errors
2 Misuse of shell builtins (according to Bash documentation)
126 Command invoked cannot execute
127 “command not found”
128 Invalid argument to exit
128+n Fatal error signal “n”
130 Script terminated by Control-C
255* Exit status out of range

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s