Reputation: 857
What is the difference between these two?
Using &&
and ||
:
command1 && command2 || command3
Using if
and else
:
if command1
then
command2
else
command3
fi
Upvotes: 2
Views: 95
Reputation: 6480
In the first example, command3 will be executed if either command1 or command2 fail: if command1 passes but command2 fails, command3 will be executed. In the if-then-else example, command3 will be executed only when command1 fails.
In other words, the first one, when translated into if-then-else becomes:
if command1
then
if !command2
then
command3
fi
else
command3
fi
With command1=true, command2=false and command3=echo 'something' you can see the difference. The &&-||
version:
true && false || echo 'something'
will yield something
as output. When using the if-then-else
version:
if true
then
false
else
echo 'something'
fi
you'll have no output.
Upvotes: 2
Reputation: 799300
The latter will always work properlyintuitively. The former has a boundary condition where both command2
and command3
can be executed.
Upvotes: 4