royvandewater
royvandewater

Reputation: 1428

How to accomplish a logical OR in bash

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.

Upvotes: 4

Views: 2339

Answers (3)

tweaksp
tweaksp

Reputation: 621

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

Upvotes: 3

Douglas Leeder
Douglas Leeder

Reputation: 53310

This should work:

command1 || command2

Upvotes: 1

Mark Rushakoff
Mark Rushakoff

Reputation: 258148

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.

Upvotes: 7

Related Questions