Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

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

For example,

$ command1 && command2

vs

$ command1; command2
like image 711
stevek-pro Avatar asked Sep 29 '22 03:09

stevek-pro


People also ask

What does double ampersand mean?

In programming, a double ampersand is used to represent the Boolean AND operator such as in the C statement, if (x >= 100 && x >= 199). In HTML, the ampersand is used to code foreign letters and special characters such as the copyright and trademark symbols. See ampersand codes and address operator.

What does the double ampersand character && do in the apt command?

What does the “&&” do? The double-ampersand is an operator telling the bash terminal to first execute the command before the && operator and if that command was successfully executed without any errors, then go ahead and execute the command after the “&&” operator.

What is the difference between & and && in bash?

In Bash—and many other programming languages— && means “AND”. And in command execution context like this, it means items to the left as well as right of && should be run in sequence in this case.


2 Answers

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.

like image 232
cdhowie Avatar answered Oct 17 '22 14:10

cdhowie


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.

like image 51
jimm-cl Avatar answered Oct 17 '22 14:10

jimm-cl