Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accomplish a logical OR in bash

Tags:

bash

logic

I'd like to have a command only execute if the preceding command's exit status was not 0.

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

like image 309
royvandewater Avatar asked Dec 22 '22 01:12

royvandewater


2 Answers

For this, use the double-pipe (||) operator.

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

The second command is only executed when the first command returns non-zero, exactly as you specified.

like image 137
Mark Rushakoff Avatar answered Jan 03 '23 00:01

Mark Rushakoff


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

       "or"          "xor"
P  Q  (( $P || $Q ))  (( ($P && ! $Q) || (! $P && $Q) ))
0  0  0               0 
0  1  1               1
1  0  1               1
1  1  1               0
like image 34
tweaksp Avatar answered Jan 03 '23 00:01

tweaksp