When a Unix program finishes, it leaves an exit code for the parent process that started the program. The exit code is a number and is sometimes called an error code. When the exit code is zero (0), this means that the program ran without problems. However, if the program has an error, it usually exits with some number other than 0.
The exit code of the last command is held in the $? special variable, so you can check it out for yourself at your shell prompt:
$ ls / > /dev/null $ echo $? 0 $ ls /asdfasdf > /dev/null ls: /asdfasdf: No such file or directory $ echo $? 1
You can see that the successful command returned 0 and the unsuccessful command returned 1.
If you intend to use the exit code of a command, you must use or store the code immediately after running the command. For example, if you run athird echo $? just after the preceding series of commands, the result would be 0 because the second of the two echo commands completed successfully.
When writing shell code that aborts a script abnormally, you should use something like exit 1 to pass an exit code of 1 back to whatever parent process ran the script. You don't necessarily have to use 1; for example, you may want to use different numbers for different conditions.
A few programs like diff and grep use nonzero exit codes to indicate normal conditions. For example, grep returns 1 if it finds something matching its pattern in its input, and 0 if not. In this case, the nonzero exit code is not an error. These commands use other exit codes for errors: grep and diff use 2 for real problems. If you think a program is using a nonstandard exit code, read its manual page. The exit codes are usually explained in the DIAGNOSTICS section.