29

Not being an expert in either Linux not Unix I'm wondering what the difference between these 2 method of stringing 2 commands on the same line? I see no difference in output in this simplistic example

Pete$date ; time
Sun Mar 17 19:37:20 EDT 2013

real    0m0.000s
user    0m0.000s
sys 0m0.000s

Pete$date &&time
Sun Mar 17 19:37:46 EDT 2013

real    0m0.000s
user    0m0.000s
sys 0m0.000s

This hasn't caused any problems - I'm just curious..

2 Answers 2

42

&& is a logical 'and'. The first argument is evaluated, and the second one is evaluated only if the first one returns true. The reason is that "false AND something" is always false, so no need to evaluate the second argument in this case.

So using && you make sure that the second command is not executed if the first one reports an error (true is represented by the exit code 0, which indicates that there was no error). In contrast, ; executes both commands, no matter what the outcome of the first one is.

Conclusion: Chaining commands with && is a good habit. In contrast to ; it won't execute subsequent commands if something went wrong.

2
  • do you mean that 0 means true or that 0 means true -- there IS an error? Mar 19, 2013 at 18:46
  • 1
    @MichaelButler: 0 means true. I've added a clarification.
    – azimut
    Mar 19, 2013 at 18:57
26

;

Sequentially executes the commands, no matter what the previous exit status was:

# sh -c "exit 0" ; echo "2nd command"
2nd command
# sh -c "exit 1" ; echo "2nd command"
2nd command

&&

Logical AND

Execute the next command, but only if the previous command succeeded (the exit status was 0):

# sh -c "exit 0" && echo "2nd command"
2nd command
# sh -c "exit 1" && echo "2nd command"
#

||

Logical OR

Execute the next command, but only if the previous command failed (the exit status was not 0):

# sh -c "exit 0" || echo "2nd command"
#
# sh -c "exit 1" || echo "2nd command"
2nd command
1
  • 6
    Also, sh -c "exit 0" can be replaced with true in these examples, and sh -c "exit 1" with false.
    – Flimm
    Mar 18, 2013 at 12:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .