How To - Determine Return Status of Shell command

[Unix] Determine Return Status of Shell command

Unix (Linux as well) has several parameters and variables that store the return status of the last command executed. It is noteworthy that these variables are system reserved and assignment to them is not allowed by user.

The $? expands to the return status of the most recently used command on the terminal.
The return status 0 signifies Successful execution of the command, whereas 127 or any non-zero value signifies Error in execution.


For Eg. When you type the below command in terminal.
$ date
Mon Feb 11 02:29:15 EST 2013
And then check for the return status using below command.
$ $?
0


This denotes that the "date" command executed successfully with return status 0.

However, if we try to type the following command, we get return status of 127.

$ daate
bash: daate: command not found
$ $?
bash: 127: command not found

 
This functionality comes handy when we want to run a command based on the return status of some other command.

Below given is an Shell script which search for the regular expression "Vishal" in the directory NewDirectory and prints appropriate output based on the return status of grep.
  cd NewDirectory
if [ $? -ne 0 ] ; then
exit
fi
grep "Vishal" *
if [ $? -eq 0 ]; then
echo "Search Successful"
else
echo "String Not Found"
exit
fi


The above script also handles the exception where the directory NewDirectory is not present and exits gracefully!
(You may want to read the complete list of System Reserved Variables here)