Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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

share|improve this question
add comment

2 Answers

up vote 43 down vote accepted

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

share|improve this answer
    
do you mean that 0 means true or that 0 means true -- there IS an error? –  Michael Butler Mar 19 '13 at 18:46
1  
@MichaelButler: 0 means true. I've added a clarification. –  azimut Mar 19 '13 at 18:57
add comment

;

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
share|improve this answer
6  
Also, sh -c "exit 0" can be replaced with true in these examples, and sh -c "exit 1" with false. –  Flimm Mar 18 '13 at 12:07
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.