Using [[ ]] for Bash Conditionals

Su Suriya Ravichandran Updated 06 Dec 2026
11 min read ·Lesson 69 of 205

Lesson 68 showed that [ ] is an ordinary command, and that its quirks come from that fact: unquoted variables can vanish or split, < needs escaping, and combining tests is awkward. Bash offers a second form, the double-bracket [[ ]], designed to remove those problems. It is not a command. It is part of the shell's own syntax, so Bash can read the whole expression before expanding anything, and that changes how it behaves.

Understanding the Concept

[[ expression ]] is a compound command that evaluates a conditional expression and returns an exit status, just like [ ] does. It can be used anywhere a condition is accepted:

if [[ $name == "Ana" ]]; then
    echo "Hello, Ana"
fi

Because [[ is a keyword rather than a command, you can confirm the difference with type:

type [[

Output:

[[ is a shell keyword

Compare that with [ is a shell builtin from lesson 68. A keyword is recognized while Bash is still parsing the line, before it performs word splitting or filename expansion. This is what makes [[ ]] safer and more expressive.

Syntax

[[ EXPRESSION ]]

As with [ ], spaces are required after [[ and before ]], and around operators. The expression can use all the string, integer and file operators from lesson 68, plus several that exist only in [[ ]]:

  • pattern matching with == and != against glob patterns,
  • regular expression matching with =~,
  • < and > string comparison without escaping,
  • &&, || and ( ) for combining tests inside one expression.

No Quoting Problems

The most visible difference is what happens to variables. Inside [[ ]], an unquoted variable is not word-split and an empty variable does not vanish:

empty=""
[[ $empty = "x" ]]; echo "empty unquoted =: $?"
[[ -n $empty ]]; echo "empty unquoted -n: $?"

v="two words"
[[ $v = "two words" ]]; echo "spaces: $?"

Output:

empty unquoted =: 1
empty unquoted -n: 1
spaces: 0

In lesson 68, the equivalent [ ] tests produced errors or the wrong answer. Here all three give the correct result: an empty string is not equal to x, -n correctly reports an empty variable as empty, and a value with a space stays in one piece.

You may still quote variables out of habit, and doing so does no harm. Quoting matters on the right side of == and =~, as the next sections show.

Pattern Matching with ==

Inside [[ ]], the right side of == and != is a glob pattern (the same wildcard syntax used for filenames, covered in lesson 52). An unquoted pattern matches by wildcard rules; a quoted pattern is compared literally.

file="report.txt"
[[ $file == *.txt ]]; echo "*.txt: $?"
[[ $file == r* ]]; echo "r*: $?"
[[ $file == *.pdf ]]; echo "*.pdf: $?"
[[ $file == "*.txt" ]]; echo "quoted pattern literal: $?"
[[ $file == ??????.txt ]]; echo "??????.txt: $?"
[[ $file == [rs]*.txt ]]; echo "[rs]*.txt: $?"

Output:

*.txt: 0
r*: 0
*.pdf: 1
quoted pattern literal: 1
??????.txt: 0
[rs]*.txt: 0

The wildcards used are * (any run of characters), ? (exactly one character), and [rs] (one character from a set). The test "*.txt" in quotes asks whether the text is literally an asterisk followed by .txt, and report.txt is not that, so the result is false.

Matching happens against the value of the variable only. The pattern is never expanded against files in the current directory, so even if files that match *.txt exist, they have no effect:

touch one.txt two.txt
pat="*.txt"
[[ $pat == "*.txt" ]]; echo "literal star: $?"

Output:

literal star: 0

The single = works the same as == inside [[ ]], and != negates the match:

[[ a = a ]]; echo "= : $?"
[[ a == a ]]; echo "== : $?"
[[ a != b ]]; echo "!= : $?"

Output:

= : 0
== : 0
!= : 0

Case Sensitivity

Matching is case-sensitive by default. The nocasematch shell option turns that off for pattern and regex matching in [[ ]]:

[[ HELLO == hello ]]; echo "case differs: $?"
shopt -s nocasematch
[[ HELLO == hello ]]; echo "nocasematch: $?"
shopt -u nocasematch

Output:

case differs: 1
nocasematch: 0

The shopt -s command switches an option on and shopt -u switches it off. Lesson 149 covers shopt. Turning an option off again afterward keeps the rest of the script predictable.

Regular Expression Matching with =~

The =~ operator matches the left side against an extended regular expression, which is a more powerful pattern language than globs. It is true if the expression matches anywhere in the text, so anchors ^ and $ are used to demand a match of the whole value.

email="ana@example.com"
if [[ $email =~ ^[a-z]+@[a-z]+\.[a-z]+$ ]]; then
    echo "looks like email"
fi

Output:

looks like email

The pattern reads: start of text, one or more lowercase letters, an @, one or more letters, a literal dot (escaped as 0 because an unescaped dot means any character), one or more letters, end of text. This is a simplified check, not a full email validator.

Capturing Parts with BASH_REMATCH

When the pattern contains parentheses, Bash saves the pieces it matched in the array BASH_REMATCH. Element 0 is the whole match, and elements 1, 2 and so on hold each parenthesized group:

if [[ "2026-11-21" =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})$ ]]; then
    echo "year=${BASH_REMATCH[1]} month=${BASH_REMATCH[2]} day=${BASH_REMATCH[3]} whole=${BASH_REMATCH[0]}"
fi

Output:

year=2026 month=11 day=21 whole=2026-11-21

{4} means exactly four of the previous item, and [0-9] is one digit. Arrays are covered in lessons 97 to 105; here it is enough to know that ${BASH_REMATCH[1]} is the text matched by the first pair of parentheses.

Keeping a Regex in a Variable

A regular expression with spaces or special characters is easier to read when stored in a variable. Use the variable unquoted on the right of =~:

re='^[0-9]+$'
[[ 123 =~ $re ]]; echo "var regex: $?"
[[ "abc" =~ ^[0-9]+$ ]]; echo "abc numeric: $?"

Output:

var regex: 0
abc numeric: 1

Quoted Regular Expressions

If you quote the right side of =~, Bash treats it as a plain string and not as a regular expression:

[[ "a.c" =~ "a.c" ]]; echo "quoted same: $?"
[[ "abc" =~ "a.c" ]]; echo "quoted dot literal on abc: $?"
[[ "abc" =~ a.c ]]; echo "unquoted dot any char: $?"

Output:

quoted same: 0
quoted dot literal on abc: 1
unquoted dot any char: 0

With the quotes, the dot must be a real dot, so abc does not match. Without the quotes, the dot means "any character", so abc matches. This is the most common surprise with =~.

Comparing Strings with < and >

< and > compare strings alphabetically, and no backslash is needed because [[ is part of the shell's syntax:

[[ apple < banana ]]; echo "apple < banana: $?"
[[ b > a ]]; echo "b > a: $?"

Output:

apple < banana: 0
b > a: 0

These are string comparisons. For numbers, they give the wrong answer:

[[ 10 < 9 ]]; echo "10 < 9 as strings: $?"
[[ 10 -lt 9 ]]; echo "10 -lt 9: $?"

Output:

10 < 9 as strings: 0
10 -lt 9: 1

As text, 10 sorts before 9 because the character 1 comes before 9, so the string comparison says "true". As numbers, 10 is not less than 9, so -lt correctly says "false". Use -lt, -gt, -eq and friends for numbers, as in lesson 73.

Combining Tests with && and ||

Inside [[ ]] you can use &&, ||, ! and parentheses directly, in a single expression:

[[ -f /etc/hostname && -r /etc/hostname ]]; echo "&&: $?"
[[ -d /etc/hostname || -f /etc/hostname ]]; echo "||: $?"
[[ ! -d /etc/hostname ]]; echo "!: $?"
[[ ( 1 -eq 1 || 1 -eq 2 ) && -d /etc ]]; echo "parens: $?"

Output:

&&: 0
||: 0
!: 0
parens: 0

Unlike -a and -o in [ ], these operators have a well-defined precedence: ! binds tightest, then &&, then ||, and parentheses override. They also short-circuit, meaning the right side of && is skipped when the left side is already false. The old -a and -o operators are not accepted in [[ ]]:

[[ 1 -eq 1 -a 2 -eq 2 ]]
s4.sh: line 1: syntax error in conditional expression
s4.sh: line 1: syntax error near `-a'

Numeric Tests Evaluate Names as Variables

The integer operators work inside [[ ]], but with a difference that can surprise you. Each side is evaluated as an arithmetic expression, so a bare word is read as a variable name, and an unset or non-numeric variable counts as 0:

[[ 7 -lt 12 ]]; echo "-lt: $?"

[[ "abc" -eq 5 ]]; echo "abc -eq 5: $?"
x=abc
[[ $x -eq 0 ]]; echo "x=abc -eq 0: $?"

a=3
[[ a -eq 3 ]]; echo "bare name a -eq 3: $?"
[ a -eq 3 ] 2>&1; echo "[ a -eq 3 ]: $?"

Output:

-lt: 0
abc -eq 5: 1
x=abc -eq 0: 0
bare name a -eq 3: 0
t69.sh: line 45: [: a: integer expression expected
[ a -eq 3 ]: 2

In [[ ]], the text abc is treated as the name of a variable that has no value, which evaluates to 0. That means [[ $x -eq 0 ]] reports true for the text abc with no error, where [ ] would complain. A bare a refers to the variable a, whose value is 3. This is flexible but easy to misread, so validate that input really is a number (with =~ ^[0-9]+$, for instance) before comparing it.

Other Operators

All the file, string and integer operators from lesson 68 work in [[ ]]. In addition, there are file comparison operators:

touch -d '2026-01-01' old.txt
touch -d '2026-06-01' new.txt
[[ new.txt -nt old.txt ]]; echo "-nt: $?"
[[ old.txt -ot new.txt ]]; echo "-ot: $?"
[[ old.txt -ef old.txt ]]; echo "-ef: $?"

Output:

-nt: 0
-ot: 0
-ef: 0

-nt means newer than, -ot means older than, and -ef means that both names refer to the same file. Command substitution works as in any other command:

[[ $(echo hi) == hi ]]; echo "cmd subst: $?"

Output:

cmd subst: 0

A single operand is true when it is a non-empty string:

[[ "" ]]; echo "[[ empty ]]: $?"
[[ x ]]; echo "[[ x ]]: $?"

Output:

[[ empty ]]: 1
[[ x ]]: 0

The -v operator tests whether a variable is set:

name=1
[[ -v name ]]; echo "-v: $?"

Output:

-v: 0

Syntax Errors

Because [[ ]] is parsed by the shell itself, mistakes are reported at parse time, and the whole line is rejected before anything runs:

[[ -f x]]; echo hi
s1.sh: line 1: syntax error in conditional expression: unexpected token `;'
s1.sh: line 1: syntax error near `;'
s1.sh: line 1: `[[ -f x]]; echo hi'

Without a space, x]] is one word and the closing ]] is never found. A missing operand is also detected immediately:

[[ -n ]]; echo $?
s3.sh: line 1: unexpected argument `]]' to conditional unary operator
s3.sh: line 1: syntax error near `;'
s3.sh: line 1: `[[ -n ]]; echo $?'

Error messages here carry the script.sh: line N: prefix that Bash prints for script files.

Portability

[[ ]] is not part of the POSIX standard. It is available in Bash, Zsh and Ksh, but not in Dash, the sh on Debian and Ubuntu:

[[ a == a ]]; echo $?

Output in Dash:

d.sh: 1: [[: not found
127

If a script starts with #!/bin/sh and may run under Dash, use [ ] with quoted variables. If it starts with #!/usr/bin/env bash, [[ ]] is the better choice. The two forms are compared again in lessons 188 and 189.

Choosing Between [ ] and [[ ]]

Need[ ][[ ]]
Works in every POSIX shellYesNo
Safe with unquoted variablesNoYes
Glob pattern matchingNoYes (==)
Regular expressionsNoYes (=~)
&& and || inside one testNo (-a, -o only)Yes
< and > without escapingNoYes

Practical Applications

A script that classifies its argument by using patterns, a regex and a file test in one elif chain:

#!/usr/bin/env bash

input="$1"

if [[ -z $input ]]; then
    echo "Usage: $0 VALUE"
elif [[ $input =~ ^[0-9]+$ ]]; then
    echo "$input is a whole number"
elif [[ $input == *.txt || $input == *.md ]]; then
    echo "$input looks like a text file name"
elif [[ -d $input ]]; then
    echo "$input is a directory"
else
    echo "$input is something else"
fi

Saved as classify.sh:

$ bash classify.sh
Usage: classify.sh VALUE
$ bash classify.sh 2026
2026 is a whole number
$ bash classify.sh notes.md
notes.md looks like a text file name
$ bash classify.sh /etc
/etc is a directory
$ bash classify.sh hello
hello is something else

Each branch uses a different capability of [[ ]]. The first handles an empty argument without quoting, the second uses =~ for a digits-only check, the third combines two glob matches with ||, and the fourth uses a file test.

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 Using [[ ]] for Bash Conditionals and get answers drawn from it.

Signed-in readers only.