exit status

From Glee
Jump to: navigation, search


Command exit status is something fundamental. It is use to know if a command succeeded, which can then also be conditionally used to run more commands, or not.

Zero means everything went fine, any other number means something went wrong. The typical simple case is 1 meaning the command failed, but some command can also return 2, 3 or more and usually document what the number means.

Checking from the shell

Just look at the $? variable. Example :

$ ls /var/empty
$ echo $?
$ $ ls /foo/nonexistent
ls: cannot access /foo/nonexistent: No such file or directory
[dude@fusion ~]$ echo $?


Command exit status is used intensively in shell scripts.

Example of simple command chaining :

# Test if the file exists, if it does test returns with zero status, so the cat is executed
test -f /tmp/foo && cat /tmp/foo
# Same as above, but if test returns a non-zero status, the cat is executed
test -f /tmp/foo || cat /tmp/foo

Example of conditional :

if cat /tmp/foo; then echo "This was the cat of /tmp/foo"; fi