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(pass, failed or partially completed) 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(builtin) variable. The exit status value varies from 0 to 255. Some of the commonly used exit status are as below.
0 Successful execution of command 1 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
[email protected]:~/Templates$ ls
[email protected]:~/Templates$ echo $?
If you get exit status as zero then 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. Please comment on this at comments section.
Latest posts by Surendra Anne (see all)
- Luke Kanies is no more Puppet CEO - September 27, 2016
- Puppet terminology for newbe Linux users - September 3, 2016
- Understanding AWS “The services” Part – II - June 8, 2016
- Understanding AWS(Amazon Web services) “The Cloud” Part – I - May 11, 2016
- 16 ls command examples for newbe - April 20, 2016