What is the difference between double-ampersand (&&) and semicolon (;) in Linux Bash?

LinuxBash

Linux Problem Overview


What is the difference between ampersand and semicolon in Linux Bash?

For example,

$ command1 && command2

vs

$ command1; command2

Linux Solutions


Solution 1 - Linux

The && operator is a boolean AND operator: if the left side returns a non-zero exit status, the operator returns that status and does not evaluate the right side (it short-circuits), otherwise it evaluates the right side and returns its exit status. This is commonly used to make sure that command2 is only run if command1 ran successfully.

The ; token just separates commands, so it will run the second command regardless of whether or not the first one succeeds.

Solution 2 - Linux

command1 && command2

command1 && command2 executes command2 if (and only if) command1 execution ends up successfully. In Unix jargon, that means exit code / return code equal to zero.

command1; command2

command1; command2 executes command2 after executing command1, sequentially. It does not matter whether the commands were successful or not.

Solution 3 - Linux

The former is a simple logic AND using short circuit evaluation, the latter simply delimits two commands.

What happens in real is that when the first program returns a nonzero exit code, the whole AND is evaluated to FALSE and the second command won't be executed. The later simply executes them both in order.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionstevek-proView Question on Stackoverflow
Solution 1 - LinuxcdhowieView Answer on Stackoverflow
Solution 2 - Linuxjimm-clView Answer on Stackoverflow
Solution 3 - LinuxDanstahrView Answer on Stackoverflow