What is the reason for using && instead of ; to place to commands on the same line?

Solution 1:

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

Solution 2:

;

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