Testing Conditions with test and [ ]

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 68 of 205

The if statement from lesson 66 runs a command and checks its exit status. To compare values, you need a command whose job is to make a comparison and report the result through its exit status. That command is test, and it has a second name written with square brackets: [. Together they handle string comparisons, number comparisons, and checks on files. They are the oldest and most portable way to write conditions in shell scripts.

Understanding the Concept

test evaluates an expression made of operators and operands. It prints nothing. Instead it exits with:

  • 0 when the expression is true,
  • 1 when the expression is false,
  • 2 when the expression itself is invalid, such as a missing operand.

The [ ... ] form is the same command, with the opening bracket as the command name and the closing bracket as a required final argument that exists only to make the line look balanced. These two lines are equivalent:

test -f /etc/hostname
[ -f /etc/hostname ]

Both examples return the same status:

test -f /etc/hostname; echo "test -f: $?"
[ -f /etc/hostname ]; echo "[ -f: $?"
[ -f /nonexistent ]; echo "missing: $?"

Output:

test -f: 0
[ -f: 0
missing: 1

How It Works

In Bash, [ and test are built-in commands, so no separate program is started when they run. Most systems also provide external programs with the same names, which is where the [ command originally lived. You can see both with type -a:

type -a [ test

Output:

[ is a shell builtin
[ is /usr/bin/[
[ is /bin/[
test is a shell builtin
test is /usr/bin/test
test is /bin/test

Bash uses the built-in version first. The paths shown here come from one Linux system and vary between machines.

Because [ is an ordinary command, the shell treats everything after it as plain words, called arguments. This one fact explains almost all the syntax rules in the rest of this lesson:

  • There must be a space after [ and before ], because they are separate words.
  • Every operator and every operand is a separate argument, so they must be separated by spaces too.
  • An unquoted variable is expanded and word-split before [ sees it, which can change the number of arguments (lesson 53 on word splitting and lesson 55 on quoting explain why).

Syntax

[ EXPRESSION ]
test EXPRESSION

Typical uses inside an if:

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

The expression is built from unary operators (one operand, such as -f file) and binary operators (two operands, such as a = b).

String Tests

String tests compare text or check whether a string is empty:

ExpressionTrue when
[ "$a" = "$b" ]the strings are equal
[ "$a" != "$b" ]the strings are different
[ -z "$a" ]the string has zero length
[ -n "$a" ]the string has non-zero length
name="Ana"
[ "$name" = "Ana" ]; echo "= : $?"
[ "$name" != "Bob" ]; echo "!= : $?"
[ -z "" ]; echo "-z empty: $?"
[ -n "$name" ]; echo "-n name: $?"
[ -z "$name" ]; echo "-z name: $?"

Output:

= : 0
!= : 0
-z empty: 0
-n name: 0
-z name: 1

The single = is the portable equality operator. Bash also accepts == inside [ ], but other shells do not (see "Portability" below). Lesson 70 covers string comparison in more detail.

Integer Tests

Numbers are compared with word-style operators, because < and > are already used for redirection:

OperatorMeaning
-eqequal
-nenot equal
-ltless than
-leless than or equal
-gtgreater than
-gegreater than or equal
a=7; b=12
[ "$a" -eq 7 ]; echo "-eq: $?"
[ "$a" -ne "$b" ]; echo "-ne: $?"
[ "$a" -lt "$b" ]; echo "-lt: $?"
[ "$a" -le 7 ]; echo "-le: $?"
[ "$a" -gt "$b" ]; echo "-gt: $?"
[ "$a" -ge 7 ]; echo "-ge: $?"

Output:

-eq: 0
-ne: 0
-lt: 0
-le: 0
-gt: 1
-ge: 0

These operators accept only integers. Anything else is an error with status 2:

[ "abc" -eq 5 ]; echo "abc -eq 5: $?"
[ "3.5" -gt 2 ]; echo "3.5 -gt 2: $?"

Output:

t68.sh: line 51: [: abc: integer expression expected
abc -eq 5: 2
t68.sh: line 52: [: 3.5: integer expression expected
3.5 -gt 2: 2

For decimal numbers use a tool such as bc or awk. Lesson 73 covers integer comparison and the (( )) form in depth.

File Tests

File operators ask a question about a path. Lessons 71 and 72 explore them fully; these are the ones used most often:

ExpressionTrue when
-e paththe path exists, of any type
-f pathit is a regular file
-d pathit is a directory
-s pathit exists and has a size greater than zero
-r pathit is readable by you
-w pathit is writable by you
-x pathit is executable by you
mkdir d; touch f; : > empty; echo hi > full
[ -e f ]; echo "-e f $?"
[ -f d ]; echo "-f d $?"
[ -d d ]; echo "-d d $?"
[ -s empty ]; echo "-s empty $?"
[ -s full ]; echo "-s full $?"
[ -x full ]; echo "-x full $?"
chmod +x full; [ -x full ]; echo "-x full after chmod $?"

Output:

-e f 0
-f d 1
-d d 0
-s empty 1
-s full 0
-x full 1
-x full after chmod 0

f exists, d is a directory and not a regular file, empty has no content, full has content, and full only becomes executable after chmod +x. When you run these tests as the administrator account (root), the -r and -w tests succeed for almost any file, because that account bypasses ordinary permission checks.

Combining Tests

There are two ways to combine tests. The first uses the shell's own && and || between separate [ ] commands, which is the style to prefer:

[ -f full ] && [ -r full ]; echo "&&: $?"

The second puts operators inside one [ ] expression: -a for AND, -o for OR, and ! for NOT:

[ -f full -a -r full ]; echo "-a: $?"
[ -d full -o -f full ]; echo "-o: $?"
[ ! -d full ]; echo "!: $?"

Output:

-a: 0
-o: 0
!: 0

The -a and -o operators work, but the POSIX standard marks them as obsolete because expressions that combine them with ! and parentheses can be parsed in ambiguous ways. Two separate [ ] commands joined by && or || always parse the same way. Lesson 74 covers logical operators.

Why Quoting Matters in Tests

Since [ receives its arguments after expansion, an unquoted variable can change the meaning of a test. Take an empty variable:

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

Output:

t68.sh: line 38: [: =: unary operator expected
unquoted empty with =: 2
unquoted empty -n: 0
quoted empty -n: 1

When $empty_var is empty and unquoted, it disappears completely. The first test becomes [ = "x" ], which has an operator in the wrong place, and fails with status 2. The second becomes [ -n ], which has only one argument, and a single non-empty argument is treated as true. That is why the unquoted -n test wrongly reports success on an empty variable.

A value containing spaces causes the opposite problem. It splits into several words:

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

Output:

t68.sh: line 43: [: too many arguments
unquoted spaces: 2
quoted spaces: 0

The unquoted form becomes [ two words = "two words" ], which has too many arguments. The rule is simple: always put variables inside double quotes in [ ] tests.

What a Single Argument Means

With only one argument between the brackets, [ returns true when that argument is a non-empty string, regardless of what the string looks like:

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

Output:

[ empty ]: 1
[ x ]: 0
[ -n ]: 0

The same rule explains a typo that silently passes. Without a space after -f, the whole text is a single non-empty word:

[ -f/etc/hostname ]; echo "no space after -f: $?"

Output:

no space after -f: 0

The test reports true even though it has checked nothing about files. Because [ returns 2 for some bad input and 0 for others, a mistake in the spacing can either produce an error or quietly give the wrong answer.

Invalid Expressions

Missing or surplus arguments make the command fail with status 2, and Bash prints a message on standard error:

[ 1 -eq ]; echo "[ 1 -eq ]: $?"
[ -f a b ]; echo "[ -f a b ]: $?"

Output:

e.sh: line 2: [: 1: unary operator expected
[ 1 -eq ]: 2
e.sh: line 3: [: a: binary operator expected
[ -f a b ]: 2

An if treats status 2 as false, so the then branch is skipped and the script continues. The message is the only sign of the problem, which is why you should watch the terminal output when you test a script. Error text in these examples carries the script.sh: line N: prefix that Bash prints when running a file; interactively it starts with bash:.

Comparing Strings with < and >

Inside [ ], the characters < and > compare strings alphabetically, but they must be escaped. Otherwise the shell treats them as redirections:

[ "apple" \< "banana" ]; echo "apple < banana: $?"
[ apple < banana ] 2>&1; echo "unescaped <: $?"

Output:

apple < banana: 0
t68.sh: line 55: banana: No such file or directory
unescaped <: 1

The unescaped version tries to open a file named banana as input. Lesson 69 shows that [[ ]] removes this need for escaping.

Portability

The [ command is part of the POSIX standard and works in every shell, but some of what Bash accepts is not portable. Running two of Bash's extras in Dash, which is the sh on Debian and Ubuntu:

[ "a" == "a" ]; echo "== in dash: $?"
[ -v x ]; echo "-v: $?"

Output in Dash:

d.sh: 1: [: a: unexpected operator
== in dash: 2
d.sh: 2: [: -v: unexpected operator
-v: 2

For scripts that must run under sh, use the single = for equality and avoid -v, which tests whether a variable is set. In Bash, -v works:

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

Output in Bash:

-v name: 0
-v nothing: 1

Lessons 188 and 189 return to portability.

Practical Applications

A script that checks its input before doing any work, using several kinds of tests together:

#!/usr/bin/env bash

file="$1"
limit="${2:-100}"

if [ -z "$file" ]; then
    echo "Usage: $0 FILE [MAX_LINES]"
    exit 1
fi

if [ ! -f "$file" ]; then
    echo "$file is not a regular file"
    exit 1
fi

lines=$(wc -l < "$file")

if [ "$lines" -gt "$limit" ]; then
    echo "$file has $lines lines, which is more than $limit"
else
    echo "$file has $lines lines"
fi

The script uses a string test (-z), a file test (-f with !), and a numeric test (-gt). The ${2:-100} form supplies a default limit of 100 when no second argument is given (lesson 45). The wc -l < "$file" form reads the file through input redirection, so wc prints only the number, with no filename.

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 Testing Conditions with test and [ ] and get answers drawn from it.

Signed-in readers only.