If a command executes successfully in bash, it has a 0 exit code. For command not found, the exit code is 127. Therefore, we can use the exit code to perform a specific action.
This tutorial will give you a few tips and tricks you can use to perform an action based on the previous command’s exit code.
Using the OR Operator
One way to execute a command if the previous command fails is to use the OR operator. Since an OR operator requires only one condition to be true, we can run the following syntax:
In the above syntax, the second command will execute even if the first command fails. Note that this is different from using && operator as it requires the first command to execute successfully.
In the above example, echo will still run despite the error caused by the name resolution in the ping command.
Here is a screenshot illustrating this:
NOTE: You can tie multiple commands using bash operators to achieve the best result. For example, you can allow sleep to execute only if ping and echo execute successfully.
In the example above, if either ping or echo fails, sleep does not execute.
Doing this can be helpful if the following command relies on the output from the previous command.
Using Exit Code
Bash allows us to get the exit code of the previously executed command. To view the exit code, enter the command:
We get 0 for a command executed correctly and 127 for a command not found in the example above.
To use the exit code for an action, we do:
if [[$? -eq 0]];
In the script above, we check if the exit code is equal to 0, indicating the command executed successfully. If true, execute a command. In this case, echo “success.” Otherwise, echo “fail.”
In this quick tutorial, we used bash operators and exit codes to execute a command if the previous command fails or succeeds.