How To Check If Last Command Was Successful In Bash

Have you ever executed a command in the Bash shell and wondered whether it was successful or not? I know I have! But fear not, my fellow Bash enthusiasts, because today I’m going to show you how to check if the last command you ran was successful or not.

Checking the Exit Status

In Bash, every command that is executed generates an exit status. This exit status indicates whether the command ran successfully or encountered an error. The convention is that an exit status of 0 means success, while any non-zero value indicates an error.

To access the exit status of the last command, you can use the special variable $?. This variable holds the exit status of the previous command and can be checked to determine if it was successful or not.

For example, let’s say we want to check if the ls command was successful. We can do so by using the following code:

ls
if [ $? -eq 0 ]; then
    echo "The command was successful"
else
    echo "The command encountered an error"
fi

By examining the value of $? inside an if statement we can perform different actions based on the success or failure of the previous command.

Using Conditional Statements

Conditional statements, such as if and else, allow us to execute specific code based on the outcome of a condition. In our case, the condition is the exit status of the previous command.

The syntax for a basic if statement in Bash is as follows:

if [ condition ]; then
    # code to execute if the condition is true
else
    # code to execute if the condition is false
fi

In our case, the condition is $? -eq 0, which checks if the exit status is equal to 0. If the condition is true, the code inside the if block is executed, indicating that the last command was successful. Otherwise, the code inside the else block is executed, indicating that the last command encountered an error.

Conclusion

Being able to check if the last command was successful or not is a valuable skill in Bash scripting. By using the $? variable and conditional statements, you can easily determine the outcome of your commands and take appropriate actions based on the result.

So next time you run a command in the Bash shell, don’t wonder if it was successful or not. With the knowledge you’ve gained today, you can confidently check the exit status and proceed with your scripting adventures!