How to execute a logical OR in bash

I want the command to be executed only if the previous command exit status was not 0.

i.e. Command 1 ^ Command 2 where command 2 is executed only if command 1 fails.

+4
source share
3 answers

To do this, use the two-pipe ( || ) operator.

 touch /asdf/fdasfds/fdasfdas || echo "Couldn't touch." 

The second command is only executed when the first command returns a nonzero value, exactly as you specified.

+7
source

I think it should be mentioned that OR does not have the same meaning as XOR ("exclusive" or "). See the truth table below.

  "or" "xor" PQ (( $P || $Q )) (( ($P && ! $Q) || (! $P && $Q) )) 0 0 0 0 0 1 1 1 1 0 1 1 1 1 1 0 
+3
source

This should work:

 command1 || command2 
+1
source

Source: https://habr.com/ru/post/1315135/


All Articles