From my upcoming book Easy Linux Commands:
Whenever a command or shell script completes successfully, it sets a hidden status code of zero. If the command is unsuccessful, it sets a nonzero hidden status code. This completion status code is known as the exit status. The exit status of the last command or script that was run is contained in the special shell variable,
Most of the time we never look at this value and instead check to see if the command did what we want or look for errors in the output of commands. In a shell script, however, we may want to check the exit status to make sure everything is going OK. The exit status of the last command can be displayed as follows:
example1.fil example2.xxx examples test.bsh umask_example.fil
$ echo $?
$ ls *.txt
ls: *.txt: No such file or directory
$ echo $?
The value of the exit code can then be used in a conditional statement or be transferred to another variable.