Technology and General Blog

Did you know that every single command you run in Linux has an exit code? This is correct even if a command terminates with an mistake. Exit values are integer values that vary from to 255. A non-zero price, i.e., a value increased than , implies the command exits with an error.

If a command executes efficiently in bash, it has a exit code. For command not discovered, the exit code is 127. For that reason, we can use the exit code to complete a distinct motion.

This tutorial will give you a handful of recommendations and tricks you can use to conduct an motion based on the earlier command’s exit code.

Using the OR Operator

One particular way to execute a command if the preceding command fails is to use the OR operator. Since an OR operator requires only 1 issue to be legitimate, we can run the adhering to syntax:

In the earlier mentioned syntax, the next command will execute even if the initial command fails. Notice that this is various from using && operator as it requires the initial command to execute successfully.

For illustration:

$ ping -c lhint || echo “Achievement”

In the higher than illustration, echo will continue to run in spite of the mistake brought about by the identify resolution in the ping command.

Right here is a screenshot illustrating this:

Observe: You can tie multiple commands employing bash operators to realize the ideal consequence. For example, you can enable sleep to execute only if ping and echo execute effectively.

$ ping -c 1 && echo “Achievement” || slumber 100

In the instance higher than, if possibly ping or echo fails, sleep does not execute.

Undertaking this can be handy if the next command depends on the output from the prior command.

Applying Exit Code

Bash makes it possible for us to get the exit code of the previously executed command. To watch the exit code, enter the command:

We get for a command executed effectively and 127 for a command not located in the illustration higher than.

To use the exit code for an action, we do:

if [[$? -eq 0]]
        echo “Achievements”
        echo “Fall short”

In the script earlier mentioned, we test if the exit code is equal to , indicating the command executed successfully. If genuine, execute a command. In this circumstance, echo “success.” Or else, echo “fail.”


In this quick tutorial, we utilised bash operators and exit codes to execute a command if the past command fails or succeeds.

Leave a Reply

Your email address will not be published. Required fields are marked *