1. Overview

When we execute a command in Linux, we get the system response, called an exit code or exit status. This exit status of the command gives us an idea about the success, failure, or other unexpected results that the command may return.

In this tutorial, we’ll discuss how to check if a command was executed successfully or not in Linux.

2. Using a Bash if Statement

The if statement evaluates the return value of the conditional expression. When we put the command as a conditional expression, it will return the exit status of the command executed.

On the successful execution, it will return a status zero. In case of failure, it will return some other status. We can use this status to check the successful execution of the command and can perform the consequent tasks, depending on the outcome:

if command; then
    consequent task on success
else
    consequent task on failure
fi

For example, let’s create a bash script to check whether a command is executed properly or not. Here, we’re checking the result of the pwd command, which displays the present working directory. Moreover, we’ll use the echo command as a consequent command to display some text as a result of the conditional expression:

#!/bin/bash 
if pwd; then
    echo "Command Executed Successfully"
else
    echo "Command Failed"
fi

On success, it should display the current directory path and display the result message:

$ ./cmd_exec_test.sh
/home/HARDIK/demo
Command Executed Successfully

From the above result, we can see that after running the script, it has successfully executed the pwd command and displayed the current directory. Also, it has displayed the result of the consequent echo command.

3. Using Special Variable $? With if Statement

The shell treats several parameters as special variables. The $? special variable expands to the exit status of the last executed command. By comparing that value with the expected one, we can check whether the command has been executed successfully or not.

We can use a binary comparison operator eq to check the outcome of the previous command, stored in the $? variable:

#!/bin/bash
pwd 
if [ $? -eq 0 ]; then
    echo "Command Executed Successfully"
else
    echo "Command Failed"
fi

On the successful execution of this script, the pwd command displays the present working directory. Also, it returns the status as zero:

$ ./cmd_exec_test.sh 
/home/HARDIK/demo
Command Executed Successfully

4. Conclusion

In this article, we discussed how to check whether the command execution was successful or not in Linux. We saw that by using the $? special variable, we can compare the return status of the last executed command. Moreover, using the if statement, we can perform consequent actions depending on the return status of the command.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.