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:
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:
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.