Command Line – Using ‘;’ vs ‘&&’ to Execute Multiple Commands

bashcommand line

In tutorials and how-to's I often see commands combined. For instance,

sudo apt-get update && sudo apt-get install pyrenamer

There seem to be four possible connectors: &, &&, || and ;. Though the & connector is clear to me (it sends a process to the background and leaves the terminal available), it is not clear what the difference is between && and ;. And I did not know of || until Kaya's comment.

The following questions deal with the difference between the two connectors, but do so mostly in the comments:

So here are a number of related questions:

  1. What is the difference between ; and &&?
  2. When should you use them respectively? It would be nice to see some use cases: if I want to run a command and then after it shutdown my computer, which connector should I choose?
  3. What are their advantages and dangers? Robie Basak mentions in a comment to this answer that a command like cd /somewhere_else; rm -Rf * can have destructive consequences if the first element in the command chain fails, for instance.
  4. If relevant, where do they come from?

Best Answer

Cheatsheet:

A; B    # Run A and then B, regardless of success of A
A && B  # Run B if and only if A succeeded
A || B  # Run B if and only if A failed
A &     # Run A in background.