Displaying the Exit status of a UNIX or Linux command

Easy Linux Commands: Working Examples of Linux Command SyntaxFrom 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:

$ ls
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.

Easy Linux CommandsFor more tips like this check out my book Easy Linux Commands, only $19.95 from Rampant TechPress.

Buy it now!

linux, unix, linux command, exit status

2 thoughts on “Displaying the Exit status of a UNIX or Linux command”

  1. Yes, often overlooked…. so I never miss it, I modify my bash command prompt to automatically include the last command status, e.g.

    export PS1=': \!,$? ; '

    this will print out a prompt such as
    : 101,1 ;
    where 101 is the history number of the current command and 1 was the status of the previous command. The ‘:’ & ‘;’ are used so prompt would be treated like a comment if it ever ends up as input to the shell (e.g. from a copy/paste)

Leave a Reply

Your email address will not be published. Required fields are marked *