Logical Operators: &&, ||, and !

Su Suriya Ravichandran Updated 06 Dec 2026
15 min read ·Lesson 74 of 205

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

FormMeaning
cmd1 && cmd2run cmd2 only if cmd1 succeeded
cmd1 || cmd2run cmd2 only if cmd1 failed
! cmdsucceed 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Logical Operators: &&, ||, and ! and get answers drawn from it.

Signed-in readers only.