Command Lists with ;, &&, and ||
A command list is a sequence of commands joined by ;, && or ||. These three operators decide whether the next command runs, and under what condition. They are the simplest form of flow control in Bash: you can run commands one after another, run a command only if the previous one succeeded, or run a command only if the previous one failed. They are the building blocks that later lessons on if statements and error handling extend.
Every example below depends on exit status. A command that succeeds returns 0, and a command that fails returns a non-zero value. The commands true and false do nothing except return 0 and 1, so they work well for demonstrations.
Understanding the Concept
When you type two commands on separate lines, Bash runs the first, then the second. The operators in this lesson let you put several commands on one line and add a rule about the exit status:
| Operator | Meaning |
|---|---|
a ; b | Run a, then run b, whatever happened to a. |
a && b | Run b only if a succeeded (status 0). |
a || b | Run b only if a failed (non-zero status). |
The && operator reads as "and then" and || reads as "or else".
Running Commands in Sequence with ;
The semicolon separates commands that run one after another. It is equivalent to a newline:
echo one; echo two; false; echo three
Output:
one
two
three
Even though false failed, echo three still ran. The semicolon does not look at the exit status. A newline in a script does the same thing, so these two lines are identical to the one above:
echo a
echo b
a
b
Running the Next Command Only on Success with &&
The && operator runs the second command only if the first one returned status 0:
true && echo "ran after success"
false && echo "should not print"
echo "status after false &&: $?"
Output:
ran after success
status after false &&: 1
The second echo never ran, and the status of the whole list is the status of the last command that was executed, which was false, so $? is 1.
This is the right tool when later steps depend on earlier ones. For example, change into a directory only if it was created:
mkdir proj && cd proj && pwd
If mkdir failed, for example because the directory already existed or the path was not writable, the cd and pwd would be skipped, and the shell would not end up in a wrong place. Using ; here would run cd regardless.
Running the Next Command Only on Failure with ||
The || operator runs the second command only if the first one failed:
false || echo "ran after failure"
true || echo "should not print"
echo "status after true ||: $?"
Output:
ran after failure
status after true ||: 0
This is the usual form for fallbacks and error messages:
ls nofile 2>/dev/null || echo "no such file"
Output:
no such file
Here the error message of ls was discarded, and the list printed its own message because ls failed.
A tidy way to create a file only when it is missing combines a test with the two operators:
[ -f nofile ] || echo "creating"; touch nofile
[ -f nofile ] && echo "exists now"
Output:
creating
exists now
The [ -f nofile ] command tests whether a regular file with that name exists. Lessons 68 and 71 cover the [ command and file tests in detail.
The Exit Status of a List
The status of a list is the status of the last command that actually ran. The four cases:
true && false; echo "status: $?"
false || true; echo "status: $?"
false && true; echo "status: $?"
true || false; echo "status: $?"
Output:
status: 1
status: 0
status: 1
status: 0
In the third and fourth lines, the second command was skipped, so the status came from the first command.
Combining && and || in One List
The operators && and || have equal precedence, and Bash evaluates the list from left to right. Each operator looks at the status of whatever ran last. Watch what these four lists print:
false || echo A && echo B
true || echo A && echo B
false && echo A || echo B
true && echo A || echo B
Output:
A
B
B
B
A
Follow the first line step by step: false fails, so || runs echo A, which succeeds, so && echo B runs as well, and both letters appear. In the second line, true succeeds, so || echo A is skipped. The list status is still 0 from true, so && echo B runs. Only B is printed. The third line prints only B, and the fourth prints only A.
The A && B || C Pattern Is Not if/else
It is tempting to read A && B || C as "if A, then B, else C". That reading is wrong when B can fail, because C then runs after a successful A:
true && false || echo "C ran even though A succeeded"
Output:
C ran even though A succeeded
The same happens with a command that does real work and fails at the end:
r() { true && { echo "B ran"; false; } || echo "C also ran"; }
r
Output:
B ran
C also ran
When a real choice between two branches is needed, an if statement is clearer and correct:
if true; then echo "B"; else echo "C"; fi
B
Lesson 66 introduces if in full. The list form is best kept for short, single-purpose checks.
Grouping Commands
To make the right-hand side of && or || run several commands, group them. Curly braces run the group in the current shell, and each command inside must end with a semicolon or a newline, with a space after the opening brace:
false && { echo X; echo Y; } || { echo "fail path 1"; echo "fail path 2"; }
Output:
fail path 1
fail path 2
Parentheses run the group in a subshell, which means changes such as cd or variable assignments do not leak out:
( cd /tmp && pwd ); pwd
The first pwd printed /tmp from inside the subshell, and the second printed the directory the shell was in before.
Practical Applications
The following examples show how scripts typically use lists.
Check that a tool is installed before using it:
command -v bash > /dev/null && echo "bash found"
command -v nosuchtool > /dev/null || echo "nosuchtool missing"
Output:
bash found
nosuchtool missing
The command command -v name prints where the command was found and returns 0, or returns non-zero if it does not exist. Output is sent to /dev/null, so only the status matters.
Create a missing file, then act on it:
f=data.txt
[[ -e $f ]] || { echo "missing $f"; }
printf 'x\n' > $f
[[ -s $f ]] && echo "$f has content"
Output:
missing data.txt
data.txt has content
Use grep -q to choose between branches:
echo "hello" | grep -q hell && echo "matched"
echo "hello" | grep -q xyz || echo "no match"
Output:
matched
no match
Stop a script when something is wrong. The following script changes directory or exits with status 3:
cd /nonexistent 2>/dev/null || { echo "cannot cd" >&2; exit 3; }
echo "not reached"
Output when saved as ex.sh and run with bash ex.sh; echo "status: $?":
cannot cd
status: 3
The message went to standard error, and the exit inside the braces ended the whole script. Lesson 118 covers exit in detail.
A helper function with || makes an error message short:
die() { echo "error: $*" >&2; return 1; }
[ -d /nonexistent ] || die "missing directory"
echo "status: $?"
Output:
error: missing directory
status: 1
Lists and Pipelines Together
A pipeline binds more tightly than && and ||. The status that the list sees is the status of the whole pipeline, which by default is the status of the last command in it:
echo "a b c" | wc -w && echo "ok"
false | true || echo "not printed because last cmd succeeded"
true | false || echo "printed because last cmd failed"
Output:
3
ok
printed because last cmd failed
The second line printed nothing because true ended the pipeline with status 0, as lesson 61 explained.
Lists with set -e
With set -e, a script stops when a command fails, but not when the failing command is part of a && or || list, except for the last command of the list. The next script shows both cases:
set -e
false || echo "handled"
echo "still running"
false && echo "no"
echo "reached after false &&"
true && false
echo "NOT reached"
Output when run as a script, followed by its status:
handled
still running
reached after false &&
e.sh status: 1
Three different outcomes appear. The first false is followed by ||, so the failure was handled and the script went on. The second false was followed by &&, so its failure was tolerated and the script went on, too. But in true && false, the failing command is the last in the list, so set -e ended the script, and the final echo never ran. Lesson 119 discusses these rules in depth.
To ignore a failure on purpose in a script that uses set -e, end the command with || true:
set -e
grep -q nomatch /etc/hostname || true
echo "script continues"
Output:
script continues
Line Continuation After && and ||
When a line ends with && or ||, Bash expects the list to continue on the next line, so long lists can be split:
true &&
echo "continued after &&"
false ||
echo "continued after ||"
Output:
continued after &&
continued after ||
An operator at the start of a line is an error:
&& echo b
Output:
bash: -c: line 1: syntax error near unexpected token `&&'
bash: -c: line 1: `&& echo b'
A double semicolon is also an error outside a case statement:
echo a;; echo b
Output:
bash: -c: line 1: syntax error near unexpected token `;;'
bash: -c: line 1: `echo a;; echo b'
The ;; token has a special meaning inside case, which lesson 75 covers.
Running a Command in the Background with &
The ampersand & is a related operator that ends a command and starts it in the background, so the shell does not wait for it. It is covered in the lessons on processes (135 and 136). A short preview:
sleep 0.1 & echo "started background"; wait
echo "after wait"
Output:
started background
after wait
The command wait made the shell pause until the background job ended.
Portability
The operators ;, && and || are part of the POSIX standard and work in Dash:
dash -c 'false || echo dash-or; true && echo dash-and'
Output:
dash-or
dash-and
The next lessons move from running commands in order to making decisions with them, beginning with the if statement.