Sometimes it is important to know whether a command has successfully completed.  To do this, you will have to check the code that returned from the command when it completed (called the exit codereturn code or exit status). Also, you will need to run commands that will return codes telling whether or not a condition is occurring or not. This will enable you to pass the information to other commands (such as, if or case statements) that will use the status to impact how they act.

Exit Status

Every command that is executed has a return (or exit) status, which up to now we have mostly ignored.  You can view the exit status using the $? variable.  A value of zero(0) generally indicates success.  A non-zero value generally indicates an error.  The return value must be checked or captured immediately in the command that follows, or it is lost.

Exit codes can be unpredictable.  The code for the same type of error may be different from one command to another.

Example 1

Example 2

Example 3