Ubuntu – the reason for using && instead of ; to place to commands on the same line

command line

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..

Best Answer

&& 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.