[Unix] Determine Return Status of Shell command
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 2013And 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
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)
No comments :
Post a Comment