Magicloud
Magicloud

Reputation: 857

What is the difference of these two ways in bash?

What is the difference between these two?

  1. Using && and ||:

    command1 && command2 || command3
    
  2. Using if and else:

    if command1  
    then  
        command2  
    else  
        command3  
    fi
    

Upvotes: 2

Views: 95

Answers (2)

Rudy Matela
Rudy Matela

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

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799300

The latter will always work properlyintuitively. The former has a boundary condition where both command2 and command3 can be executed.

Upvotes: 4

Related Questions