Bash Shell Scripting/Exit Status

When a process completes, it returns a small non-negative integer value, called its exit status or its return status, to the operating system. By convention, it returns zero if it completed successfully, and a positive number if it failed with an error. (This approach allows multiple different errors to be distinguished by using different positive numbers.) A Bash script can obey this convention by using the built-in command. The following command:

terminates the shell script, returning an exit status of four, indicating some sort of error. When no exit status is specified (either because  is run with no argument, or because the script ends without calling  ), the script returns the exit status of the last command it ran.

One way that exit statuses are used is with the Bash operators  ("and") and   ("or"). If two commands are separated by, then the command on the left is run first, and the command on the right is only run if the first command succeeds. Conversely, if they are separated by, then the command on the right is only run if the command on the left fails.

For example, suppose we want to delete the file  and recreate it as a blank file. We can delete it using the common Unix utility  ("remove"), and recreate it using the common Unix utility  ; so, we might write this:

But really, if  fails, we don't want to run  : we don't want to recreate the file if we failed to delete it to begin with. So, we can write this instead:

This is the same as before, except that it won't try to run  unless   has succeeded.

A third Boolean-like operator,  ("not"), inverts the exit status of a command. For example, this command:

is equivalent to, except that it will indicate success if   indicates failure, and vice versa. (This is not usually useful when exit statuses are used as actual exit statuses, indicating success or failure, but we will soon see some extended uses of exit statuses where a "not" operation is more useful.)

The exit status of a command is (briefly) available as. This can be useful when it is necessary to distinguish between multiple different failure statuses; for example, the  command (which searches for lines in a file that match a specified pattern) returns 0 if it finds a match, 1 if it finds no matches, and 2 if a genuine error occurs.