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.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.