Logical Operators: &&, ||, and !
Real decisions are rarely based on a single fact. A script may need a file that exists and is readable, an argument that is -h or --help, or a command that did not succeed. Bash handles these combinations with three logical operators: && for AND, || for OR, and ! for NOT. They appear in three different places, command lists, test brackets and arithmetic expressions, and they follow slightly different rules in each. This lesson explains all three places and the traps that go with them.
Understanding the Concept
Every operator in this lesson works with truth values, and in Bash a truth value is an exit status. Status 0 means true (success) and any other status means false (failure), as in lesson 66.
- AND (
&&) is true only when both sides are true. - OR (
||) is true when at least one side is true. - NOT (
!) reverses a single truth value.
The operators && and || do not evaluate both sides blindly. They stop as soon as the answer is known, which is called short-circuit evaluation. That makes them useful for more than combining conditions, because the right-hand side is a command that runs only when the left-hand side gives the right result.
Syntax
| Form | Meaning |
|---|---|
cmd1 && cmd2 | run cmd2 only if cmd1 succeeded |
cmd1 || cmd2 | run cmd2 only if cmd1 failed |
! cmd | succeed if cmd failed, fail if cmd succeeded |
[ cond1 ] && [ cond2 ] | two separate tests joined by AND |
[[ cond1 && cond2 ]] | AND inside a single [[ ]] |
[[ cond1 || cond2 ]] | OR inside a single [[ ]] |
[ ! cond ] and [[ ! cond ]] | negate a test |
(( expr1 && expr2 )) | AND inside arithmetic |
The && and || Operators in Command Lists
Lesson 65 introduced command lists. Here is a compact reminder of how they decide what to run:
true && echo "A ran"
false && echo "B ran"
false || echo "C ran (after false)"
true || echo "D ran"
Output:
A ran
C ran (after false)
Only two of the four echo commands run. A runs because true succeeded. B is skipped because false already made the AND false. C runs because false failed. D is skipped because true already made the OR true.
The exit status of the whole list is the status of the last command that actually ran:
true && false; echo "true && false: $?"
false || true; echo "false || true: $?"
false && true; echo "false && true: $?"
true || false; echo "true || false: $?"
Output:
true && false: 1
false || true: 0
false && true: 1
true || false: 0
In false && true, the right side never runs, so the status is that of false, which is 1. In true || false, the right side is skipped, so the status is 0.
Chains Are Evaluated from Left to Right
Mixing && and || in one line does not follow the usual arithmetic habit of "AND before OR". The two operators have the same precedence and are applied from left to right:
true || echo X && echo Y
false && echo X || echo Y
Output:
Y
Y
In the first line, true || echo X succeeds without running echo X. That result, status 0, then feeds && echo Y, which runs. In the second line, false && echo X fails without running echo X, and the || that follows reacts to that failure. Both lines print Y.
Why A && B || C Is Not an if/else
A frequent shortcut is condition && do_this || do_that, which looks like "if condition then do_this else do_that". It is not the same thing:
true && echo one || echo two
false && echo one || echo two
Output:
one
two
That works while echo one succeeds. The trouble appears when the middle command fails:
ok() { echo "ok() ran"; return 1; }
true && ok || echo "fallback ran because ok failed"
Output:
ok() ran
fallback ran because ok failed
The condition was true, yet the "else" part also ran, because || reacts to the failure of ok, not to the condition. If the middle command can fail, use a real if statement:
if true; then
ok
else
echo "else branch"
fi
Output:
ok() ran
The if form runs exactly one branch, no matter what the commands inside it return. Use && and || for short guard lines, and if when both outcomes matter.
The ! Operator
The word ! in front of a command or pipeline reverses its exit status:
! true; echo "! true: $?"
! false; echo "! false: $?"
Output:
! true: 1
! false: 0
This is useful with commands whose success you do not want, such as checking that a pattern does not appear in a file:
printf 'hello\n' > notes.txt
if ! grep -q zzz notes.txt; then
echo "zzz not in notes.txt"
fi
Output:
zzz not in notes.txt
The grep -q command returns 1 when it finds no match, and ! turns that into success, so the then branch runs. The ! must be followed by a space. Written without one, Bash looks for a command named !true:
bash -c '!true; echo "status $?"'
Output:
bash: line 1: !true: command not found
status 127
In an interactive shell, an exclamation mark followed immediately by text can also trigger history expansion, which pastes in an earlier command. Typing ! cmd with a space avoids both problems.
There is one more property, which lesson 119 explains with set -e: a command negated with ! does not end a script when its negated status is a failure. In a test run, a script with set -e kept running after both ! true and ! false.
Negation Inside Tests
Inside [ ] and [[ ]], the ! operator negates the test that follows it:
[ ! -e missing.txt ]; echo "[ ! -e missing.txt ]: $?"
[ ! "a" = "b" ]; echo "[ ! a = b ]: $?"
[ "a" != "b" ]; echo "[ a != b ]: $?"
[[ ! -e notes.txt ]]; echo "[[ ! -e notes.txt ]]: $?"
[[ ! 5 -gt 3 ]]; echo "[[ ! 5 -gt 3 ]]: $?"
Output:
[ ! -e missing.txt ]: 0
[ ! a = b ]: 0
[ a != b ]: 0
[[ ! -e notes.txt ]]: 1
[[ ! 5 -gt 3 ]]: 1
The first line is true because the file does not exist. The next two show two ways to say "not equal"; the dedicated != operator is easier to read. In the last two lines, the tests themselves are true (the file exists, five is greater than three), and ! flips them to false.
Combining Conditions Inside [[ ]]
The [[ ]] keyword accepts && and || directly, so a compound condition fits in one pair of brackets:
x=5
[[ -e notes.txt && -s notes.txt ]]; echo "exists and non-empty: $?"
[[ -e missing.txt || -e notes.txt ]]; echo "either exists: $?"
[[ $x -ge 1 && $x -le 10 ]]; echo "x in range 1 to 10: $?"
[[ $x -lt 1 || $x -gt 10 ]]; echo "x outside the range: $?"
Output:
exists and non-empty: 0
either exists: 0
x in range 1 to 10: 0
x outside the range: 1
Inside [[ ]], && and || short-circuit just like the ones in command lists, and the precedence is the one you would expect from logic: ! binds tightest, then &&, then ||. You can group parts with parentheses:
[[ a == a || b == c && d == e ]]; echo "T || F && F: $?"
[[ ( a == a || b == c ) && d == e ]]; echo "(T || F) && F: $?"
[[ ! a == b && c == c ]]; echo "! F && T: $?"
Output:
T || F && F: 0
(T || F) && F: 1
! F && T: 0
The first test is true because && is applied before ||: b == c && d == e is false, and a == a || false is true. Parentheses change the grouping in the second test, so the result becomes false. In the third, ! applies only to a == b, which makes the left part true.
Notice the difference from command lists. In a command list, && and || have equal precedence. Inside [[ ]], && binds tighter than ||. Writing parentheses whenever both appear removes any doubt.
Combining Conditions with [ ]
The [ command does not understand && and || as part of its own syntax, because the shell would read them as list operators and split the command in two. The portable method is to write two tests and join them with the shell's operators:
[ "$x" -ge 1 ] && [ "$x" -le 10 ]; echo "range: $?"
[ "$x" -lt 1 ] || [ "$x" -gt 10 ]; echo "outside: $?"
Output:
range: 0
outside: 1
The [ ] command also has its own operators -a (AND) and -o (OR), which still work in Bash:
[ "$x" -ge 1 -a "$x" -le 10 ]; echo "-a: $?"
[ "$x" -lt 1 -o "$x" -gt 10 ]; echo "-o: $?"
Output:
-a: 0
-o: 1
They are best avoided in new scripts. The operators can be mistaken for the unary -a file test from lesson 72, and the rules for parsing a long expression become unpredictable when a value looks like an operator. They are also not accepted inside [[ ]]:
[[ 5 -ge 1 -a 5 -le 10 ]]
Output:
bash: -c: line 1: syntax error in conditional expression
bash: -c: line 1: syntax error near `-a'
The error comes from bash -c, so it begins with bash: -c: line 1:. In a script file, the first part would be the script name. Use && and || between tests instead.
Logical Operators in Arithmetic
The (( )) command and $(( )) expansion also understand &&, || and !, with C-like rules. A non-zero value counts as true and zero as false:
(( 1 && 0 )); echo "(( 1 && 0 )): $?"
(( 1 || 0 )); echo "(( 1 || 0 )): $?"
(( !0 )); echo "(( !0 )): $?"
(( !5 )); echo "(( !5 )): $?"
Output:
(( 1 && 0 )): 1
(( 1 || 0 )): 0
(( !0 )): 0
(( !5 )): 1
Remember that (( )) succeeds when its result is not zero. The value of a logical expression is 1 for true and 0 for false, which $(( )) prints as text:
echo $(( 3 > 2 )) $(( 2 > 3 )) $(( 1 && 0 )) $(( 1 || 0 )) $(( !4 ))
Output:
1 0 0 1 0
Here every comparison turns into 1 or 0, and !4 is 0 because four is a true value. Inside arithmetic, no space is required after !, because the ! is part of an arithmetic expression instead of a command.
Short-Circuit Evaluation in Practice
Short-circuiting means that a command on the right might never run. A counter function makes this visible:
cnt=0
bump() { cnt=$((cnt + 1)); return "$1"; }
bump 0 || bump 0; echo "after 0 || ...: cnt=$cnt"
cnt=0; bump 1 || bump 0; echo "after 1 || ...: cnt=$cnt"
cnt=0; bump 1 && bump 0; echo "after 1 && ...: cnt=$cnt"
Output:
after 0 || ...: cnt=1
after 1 || ...: cnt=2
after 1 && ...: cnt=1
The function bump adds one to cnt and returns the status given as its argument (functions are covered in lessons 88 to 91). In the first line, bump 0 succeeds, so || never runs the second call. In the second, bump 1 fails and || runs the second call. In the third, bump 1 fails, so && skips the second call.
This is why these operators work as guards. A guard that avoids running an expensive command is only as good as the order of its conditions, because the cheap test should come first.
Grouping Commands
To run several commands as the right-hand side of && or ||, wrap them in braces. The braces group the commands without starting a new process:
{ echo one; echo two; } && echo "group ok"
false || { echo "cleanup"; echo "more cleanup"; }
Output:
one
two
group ok
cleanup
more cleanup
The opening brace must be followed by a space, and the last command inside must end with a semicolon or a newline before the closing brace. Parentheses ( ) also group commands, but they run them in a subshell, so changes such as cd do not affect the main script:
( cd /tmp && pwd ); pwd
Output:
/tmp
/home/ana/project
The first pwd runs inside the subshell and reports /tmp. The second runs in the original shell, which never changed directory, so it prints the original location. The second line of output shows an example path, because it depends on where you run the commands.
De Morgan's Laws
When a negated condition becomes hard to read, you can rewrite it. De Morgan's laws say that "not (A and B)" is the same as "not A or not B", and that "not (A or B)" is the same as "not A and not B". A truth table in Bash shows both forms agree:
for a in 0 1; do
for b in 0 1; do
[ "$a" -eq 1 ] && [ "$b" -eq 1 ]; r1=$?
! { [ "$a" -ne 1 ] || [ "$b" -ne 1 ]; }; r2=$?
echo "a=$a b=$b and=$r1 demorgan=$r2"
done
done
Output:
a=0 b=0 and=1 demorgan=1
a=0 b=1 and=1 demorgan=1
a=1 b=0 and=1 demorgan=1
a=1 b=1 and=0 demorgan=0
Both columns match on every row. The practical use is clarity: [ ! -f "$f" ] || [ ! -r "$f" ] means "the file is missing or unreadable", and it is the exact opposite of [ -f "$f" ] && [ -r "$f" ].
Logical Operators and set -e
Lesson 119 will cover set -e in detail, but the interaction with these operators is worth knowing now. A script run with set -e exits when a simple command fails, with several exceptions. A failing command that is not the last one in an && or || list does not end the script, but the last command of a list can:
set -e
false || echo "survives false in ||"
false && echo "never"
echo "survives false && ..."
true && false
echo "not reached"
Output:
survives false in ||
survives false && ...
The script ends with exit status 1 at true && false, because the failing false is the final command of the list. The earlier lines are safe: false || ... runs the echo and succeeds, and false && echo leaves the failure of false as part of the condition. A command negated with ! never triggers an exit.
Portability
All three operators work in Dash, the shell behind sh on Debian and Ubuntu, for command lists and for [ ]:
dash &&
dash ||
dash !
dash -a
dash [ ! ]
The [[ ]] keyword does not exist there, so [[ 1 == 1 && 2 == 2 ]] fails with [[: not found and status 127. For portable scripts, use two [ ] tests joined by && or ||, and use if ! command for negation. The -a and -o operators worked in this Dash test too, although the POSIX standard marks them as obsolete.
Practical Applications
Guard clauses at the top of a script stop early when something is wrong. Using || with a braced group keeps each check on one or two lines:
#!/usr/bin/env bash
file=$1
[ -f "$file" ] || { echo "error: $file is not a file" >&2; exit 1; }
[ -r "$file" ] || { echo "error: cannot read $file" >&2; exit 1; }
wc -l < "$file"
Run with notes.txt, which contains one line, the script prints 1. Run with a name that does not exist, it prints error: nothing is not a file on standard error and exits with status 1. The two guards are checked in order, so the readability test runs only when the first one passed.
Setting a default value only when a variable is empty:
name=""
[ -n "$name" ] || name="guest"
echo "name=$name"
Output:
name=guest
Combining a command with a test inside an if. The first line succeeds only when both parts are true, while the second needs just one:
if grep -q hello notes.txt && [ -s notes.txt ]; then
echo "has hello and non-empty"
fi
if grep -q zzz notes.txt || [ -s notes.txt ]; then
echo "zzz or non-empty"
fi
Output:
has hello and non-empty
zzz or non-empty
In the second if, grep finds no match and returns 1, so || tries the second condition, which is true because the file is not empty.