BASH Programming

How To Check the Exit Status Using an ‘if’ Statement in Bash

In Bash scripting, the exit status of a command or script is an important piece of information that can determine the success or failure of a script or a particular command. A command or script’s exit status, which is a numeric value, shows whether it was successful or encountered an error. This article will examine how to use a ‘if’ statement in Bash to check the exit status.

Checking the exit status using an ‘if’ statement in Bash

Using a “if” statement and the “$?” variable, we can determine whether a command or script has executed successfully. Which holds the exit status of the most recent command executed, the syntax of the “if” statement for determining the exit status is as follows:

if [ $? -eq 0 ]
then
    echo "execution sucessfull"
else
    echo "execution failed"
fi

The ‘-eq’ operator is used to check if the exit status is equal to zero or not, which indicates that the command or script has completed successfully.

If the exit status is not equal to zero, the ‘else’ block is executed, which prints a message indicating that the command has failed. Here’s a simple example to illustrate how we can use an ‘if’ statement to check the exit status of a command:

#!bin/bash
ls /false-directory
if [ $? -eq 0 ]
then
    echo "execution suncessfull"
else
    echo "execution failed"
fi

To list the contents of a non-existent directory I am using the ‘ls’ command and since the directory does not exist, the ‘ls’ command will fail, and its exit status will be non-zero. The ‘if’ statement then checks the exit status using the ‘$?’ variable and prints a message indicating that the command has failed:

Conclusion

Checking the exit status of a command or script is an important part of Bash scripting and using an ‘if’ statement along with the ‘$?’ variable is a simple and effective way to check the exit status. By mastering this technique, we can easily determine the success or failure of a command or script and take appropriate actions based on the exit status.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.