The exit status

In shell scripting, we need to check if the last command has successfully executed or not, for example, whether a file or directory is present or not. As per the result, our shell script will continue processing.

For this purpose, the bash shell has one status variable ?. The status of the last command execution is stored in ?. The range of numerical values stored in ? will be from 0 to 255. If successful in execution, then the value will be 0; otherwise, it will be non-zero, which is as follows:

    $ ls
    $ echo $?

Here, zero as the return value indicates success.

In the next case, we see the following:

    $ ls /root
    ls: cannot open directory /root: Permission denied
    $ echo $?

Here, a non-zero value indicates an error in the ...

Get Learning Linux Shell Scripting - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.