What is the difference between ampersand and semicolon in Linux Bash?
For example,
$ command1 && command2
vs
$ command1; command2
What is the difference between ampersand and semicolon in Linux Bash?
For example,
$ command1 && command2
vs
$ command1; command2
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.
&&
different from a single ampersand &
in bash?
Jan 16, 2017 at 21:40
&
causes the command to be run in the background, so yes. "Run this in the background" is very different from "run this next command only if this other one succeeds."
a;b
means "run a
and then run b
." a&&b
means "run a
, and then run b
only if a
was successful."
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
executes command2
after executing command1
, sequentially. It does not matter whether the commands were successful or not.
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.
cmd1 ; cmd2
... runs cmd1 then cmd2.
cmd1 && cmd2
... runs cmd2 if cmd1 exited with a code of zero.
Both yield a status code of the last executed command.
However, what other answers miss...
You might think that cmd1 && cmd2
and (cmd1 && cmd2)
are identical. In fact, they're very different. As is which command fails without the parens.
Consider the following. The status codes are determined by uncommenting set -e
#!/bin/bash
set -e # exit on error
set -x
# false # Yields status 1 and would cause the script to exit if -x is left uncommented
true && true # Does not exit script! Good
echo A $? # 0
false && true # Does not exit script! Wut?
echo B $? # 1
true && false # Exits the script. Wut? Wut?
echo C $? # 1, if not -e
(false && true) # Exits the script
echo D $? # 1, if not -e
(true && false) # Exits the script
echo E $? # 1, if not -e
D and E make sense, and the difference with the others makes sense - parens creates a subshell. However that both of the following yield a status of 1, but that only the seconds exits the script is truly bizarre:
false && true
true && false