Pages

Thursday, 25 August 2011

How to find a exit status of script or command in linux


Want to write meaningful scripts and become good Shell scripting expert? Then this post is for you.
In Linux/Unix when you execute a command or a script, they will exit with a meaning full exit status for your understanding purpose. So that we can take necessary actions on the out come of those commands.
In linux some command are there which will not show the output, for example “mount -a”command which we use after editing fstab file which will not show any output. So at this point how we can get exit status of such commands to know about the success of that command execution?
For this we have inbuilt variable in Linux/Unix which will store the exit status of any command or script executed. The exit status is stored in “$?” internal variable.
the exit status value varies from 0 to 255.
Some of the commonly used exit status
0 Successful execution of command

0 > command fails because of an error during expansion or redirection,
the exit status is greater than zero.

2 Incorrect command usage

126 Command found but not executable

127 Command not found
Some examples on how to use exit status..
How can I use this exit status for checking commands?
Execute a command then execute echo $? command to check the status of executed command as shown below
Example 1:
surendra@Krishna:~/Templates$ ls
New.doc
surendra@Krishna:~/Templates$ echo $?
0
so you get exit status as zero, so the command executed successfully.
How can I use exit status in shell Scripting?
We will use exit status in scripting bit different as shown below
ls -lrt

if [ $? -eq 0 ]

then

echo "the ls -lrt command executed successfully"

else

echo "the ls -lrt command not executed properly and exit status is : $?"

fi
if you see if statement is checking exit status of ls -lrt command to execute if statement. Please comment on this at comments section.

No comments:

Post a Comment

Twitter Bird Gadget