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
Example 1:
surendra@Krishna:~/Templates$ ls
New.doc
surendra@Krishna:~/Templates$ echo $?
0
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)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020 - FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018