Is there a difference between the '&&' and ';' symbols in a standard BASH terminal?

They seem to both signal BASH to commence with another command following the symbols but is there a distinct difference?


Solution 1:

With this line:

command1 && command2

command2 will be executed if (and only if) command1 returns exit status zero, whereas in this line:

command1 ; command2

both command1 and command2 will be executed regardless. The semicolon allows you to type many commands on one line.

Solution 2:

You can try the difference for yourself:

  1. ls /invalid/path && echo "hello!"
    since /invalid/path doesn't exist, ls can't show you the directory listing. It will fail with an error message: "ls: /invalid/path: No such file or directory".
    The second half of the command (echo "hello!") is never even executed because the first half failed.

  2. ls /invalid/path ; echo "hello!"
    The same error message appears as before, but this time, the second part is executed!
    ls: /invalid/path: No such file or directory
    hello!

Why is this useful?
Suppose you want to extract a file called archive.tar.gz
You could use the command tar zxvf archive.tar.gz && rm archive.tar.gz.
If for any reason the extraction of the archive fails, the second part isn't executed! You can try again.

If you use ; in the same situation, the archive is deleted and you can't try again.

Solution 3:

&& is AND, meaning that the second command will only execute if the first one returned true (no errors).