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 $?
    0

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 $?
    2

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

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.