Sobes.tech
Junior — Middle

How to implement a condition in bash where one of two commands or conditions is executed?

sobes.tech AI

Answer from AI

In bash, to execute one of two commands or conditions, you can use the logical operators || (OR) and && (AND). To execute one of two commands if the first fails, use ||:

command1 || command2

This means: execute command1, and if it ends with an error (return code not 0), then execute command2.

If you want to execute a command when both conditions are true, use &&:

command1 && command2

For more complex conditions, you can use the if construct:

if command1; then
    echo "Command 1 succeeded"
else
    echo "Command 1 failed, executing command 2"
    command2
fi

Thus, to choose one of two commands depending on the result of the first, it is convenient to use || or the conditional operator if.