Comparing Strings in Bash

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

Most of what a shell script handles is text: names, paths, answers typed by a user, output captured from other commands. Deciding what to do with that text usually means comparing it with something else. Is the answer yes? Does the filename end in .log? Is the variable empty? Bash offers several ways to compare strings, and each one has a small set of rules that decide whether the result is what you expected.

Understanding the Concept

A string comparison asks a question about characters, not about meaning. Two strings are equal only if they have exactly the same characters in exactly the same order. That includes upper and lower case, spaces at the beginning or end, and any invisible characters such as tabs or newlines.

Every comparison in Bash works the same way as the conditions in lessons 66 to 69: it is a command or keyword that returns an exit status of 0 for true and non-zero for false. Strings are compared with the [ ] command from lesson 68 or with the [[ ]] keyword from lesson 69.

Testing Equality and Inequality

The operators are = for equal and != for different. Quote the variables inside [ ], as lesson 68 explained:

a="Linux"; b="linux"
[ "$a" = "$b" ]; echo "case-sensitive =: $?"

Output:

case-sensitive =: 1

The two strings differ in the first letter, so they are not equal. Comparisons are case-sensitive by default.

To ignore case, convert both sides to the same case first. Bash 4 and later can do this with parameter expansion: ${var,,} makes the text lowercase and ${var^^} makes it uppercase.

[ "${a,,}" = "${b,,}" ]; echo "lowercased =: $?"
[ "${a^^}" = "${b^^}" ]; echo "uppercased =: $?"

Output:

lowercased =: 0
uppercased =: 0

These two forms are Bash-specific. In Dash, the ${x,,} syntax is an error:

d.sh: 2: Bad substitution

For code that must run under sh, use tr instead:

up=$(printf '%s' "$a" | tr '[:upper:]' '[:lower:]')
echo "$up"

Output:

linux

Another way to ignore case in Bash is the nocasematch option for [[ ]], shown in lesson 69.

Whitespace Counts

Spaces are characters like any other, so one extra space makes two strings different:

[ "yes" = "yes " ]; echo "trailing space: $?"
[ "yes" = " yes" ]; echo "leading space: $?"

Output:

trailing space: 1
leading space: 1

This is a common source of confusing failures when the text comes from a file, a user, or a command. A line with an invisible trailing space looks identical on screen but does not match.

Text produced by command substitution has a special rule: $(...) removes trailing newlines (lesson 48). That is why command output compares as you would hope:

out=$(printf 'ok\n\n\n')
[ "$out" = "ok" ]; echo "trailing newlines stripped: $?"

Output:

trailing newlines stripped: 0

Empty Strings and Unset Variables

The -z operator is true when a string has zero length, and -n is true when it does not:

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

Output:

-n empty: 1
-n a: 0

An empty variable and a variable that was never set both have a zero-length value, so -z cannot tell them apart:

unset u; e=""
[ -z "$u" ]; echo "-z unset: $?"
[ -z "$e" ]; echo "-z empty: $?"

Output:

-z unset: 0
-z empty: 0

If you need to know whether a variable is set at all, use the ${var+x} expansion. It produces x when the variable is set (even if empty) and nothing when it is unset:

[ -z "${u+x}" ]; echo "unset test: $?"
[ -z "${e+x}" ]; echo "empty is set, so not unset: $?"

Output:

unset test: 0
empty is set, so not unset: 1

The first test is true because u is unset. The second is false because e is set to an empty value. This builds on the default-value operators from lesson 45.

Numbers Are Strings Too

The = operator compares characters, not values. Two numbers that look different as text are different strings even when they are numerically equal:

[ "10" = "10" ]; echo "10 = 10: $?"
[ "10" = "010" ]; echo "10 = 010 as strings: $?"
[ 10 -eq 010 ]; echo "10 -eq 010 numeric: $?"
[ "1.0" = "1" ]; echo "1.0 = 1 strings: $?"

Output:

10 = 10: 0
10 = 010 as strings: 1
10 -eq 010 numeric: 0
1.0 = 1 strings: 1

When both sides are meant to be numbers, use the integer operators -eq, -lt and the rest, from lessons 68 and 73. Use = and != only when you want an exact text match.

Ordering Strings

The operators < and > compare strings in dictionary order. Inside [ ] they must be escaped with a backslash so that the shell does not treat them as redirections. Inside [[ ]] no escape is needed.

[ "apple" \< "banana" ]; echo "apple < banana: $?"
[[ apple < banana ]]; echo "apple < banana in [[ ]]: $?"

Output:

apple < banana: 0
apple < banana in [[ ]]: 0

The exact order depends on the system's locale, which is the setting that controls how text is sorted. In the plain C locale, every upper-case letter sorts before every lower-case letter, so Zebra comes before apple:

[ "Zebra" \< "apple" ]; echo "Zebra < apple: $?"

Output in the C locale:

Zebra < apple: 0

Other locales may order letters differently, ignoring case at the first comparison. When a script depends on a specific order, set LC_ALL=C for that command, or avoid depending on text order. The comparison operators are rarely needed for everyday decisions; checking equality and patterns covers most real tasks.

Checking String Length

The length of a string is available with ${#var}, which you can compare with integer operators:

s="hello"
echo "length: ${#s}"
[ "${#s}" -eq 5 ]; echo "length 5: $?"
[ "${#s}" -gt 3 ]; echo "length > 3: $?"

Output:

length: 5
length 5: 0
length > 3: 0

This is a typical way to enforce a minimum or maximum length, such as a password rule or a limit on the size of a name.

Matching Part of a String

Equality needs the whole string to match. To check whether a string starts with, ends with, or contains something, use a pattern in [[ ]] (lesson 69):

s="hello"
[[ $s == h* ]]; echo "starts with h: $?"
[[ $s == *llo ]]; echo "ends with llo: $?"
[[ $s == *ell* ]]; echo "contains ell: $?"
[[ $s != *x* ]]; echo "does not contain x: $?"

Output:

starts with h: 0
ends with llo: 0
contains ell: 0
does not contain x: 0

The * stands for any run of characters, including none. A pattern with * at both ends asks whether the text contains the middle part anywhere.

The case statement (lesson 75) matches the same patterns and is often tidier when one variable is compared with several alternatives:

case $s in
    h*) echo "case: starts with h" ;;
esac

Output:

case: starts with h

For rules that glob patterns cannot express, such as "one or more digits", use a regular expression with =~:

[[ "abc123" =~ [0-9]+ ]]; echo "has digits: $?  match=${BASH_REMATCH[0]}"

Output:

has digits: 0  match=123

Special Characters in Strings

Characters such as * and ? have a pattern meaning in some tests and not in others. The safest rule is to know which side of the operator is a pattern:

  • In [ ], both sides are plain text, so * is just an asterisk.
  • In [[ ]], the right side of == is a pattern unless it is quoted.
p='a*b'
[ "$p" = 'a*b' ]; echo "literal star in [ ]: $?"
[[ $p == 'a*b' ]]; echo "quoted literal in [[ ]]: $?"
[[ axxb == $p ]]; echo "unquoted pattern variable matches axxb: $?"
[[ axxb == "$p" ]]; echo "quoted variable does not: $?"

Output:

literal star in [ ]: 0
quoted literal in [[ ]]: 0
unquoted pattern variable matches axxb: 0
quoted variable does not: 1

The last two lines show the same variable used two ways. Unquoted on the right of ==, $p holds a pattern, and a*b matches axxb. Quoted, the text must match exactly, and axxb is not the three characters a*b. Quote the right side when you want a literal comparison, and leave it unquoted only when you want a pattern.

Strings that begin with a dash can look like operators. Bash handled all of these correctly in this test:

x="-n"
[ "$x" = "-n" ]; echo "-n operand compared: $?"
[[ $x == "-n" ]]; echo "[[ handles it: $?"
x="!"
[ "$x" = "!" ]; echo "! operand: $?"

Output:

-n operand compared: 0
[[ handles it: 0
! operand: 0

Older scripts add a prefix to both sides, such as [ "x$x" = "x-n" ], to protect against this problem in shells that parse such values as operators. Modern Bash does not need that trick, but you may meet it in older scripts.

A string can also contain a newline, which you can test for with the $'...' quoting form:

nl=$'line1\nline2'
[[ $nl == *$'\n'* ]]; echo "contains newline: $?"

Output:

contains newline: 0

What Goes Wrong Without Quotes

Quoting protects a comparison from word splitting. Without quotes in [ ], an empty variable disappears and a value with spaces becomes several words:

s=""
[ $s = "" ]; echo "unquoted empty = empty: $?"
t="a b"
[ $t = "a b" ]; echo "unquoted spaces: $?"

Output:

e.sh: line 2: [: =: unary operator expected
unquoted empty = empty: 2
e.sh: line 4: [: too many arguments
unquoted spaces: 2

Both cases should have been true, and both fail with status 2. Quoting both sides, [ "$s" = "" ], fixes them. Inside [[ ]], the left side does not need quotes, as lesson 69 showed.

Error messages in these examples show the script.sh: line N: prefix that Bash prints for script files. In an interactive terminal the prefix is bash:.

Portability

The single = works in [ ] in every shell. The double == works in Bash but is rejected by Dash (lesson 68). The < and > operators in [ ] and the pattern matching in [[ ]] are also not guaranteed to exist in other shells. For scripts that must run under sh, use = and != with quoted variables, and use case for pattern matching, because case is part of the POSIX standard.

Practical Applications

A confirmation prompt that accepts several spellings of "yes" and "no", ignores upper and lower case, and rejects anything else:

#!/usr/bin/env bash

read -r -p "Continue? (y/n) " answer
answer="${answer,,}"

if [[ $answer == y || $answer == yes ]]; then
    echo "Continuing"
elif [[ $answer == n || $answer == no ]]; then
    echo "Stopping"
else
    echo "Please answer y or n"
fi

A session in a terminal:

$ bash confirm.sh
Continue? (y/n) YES
Continuing
$ bash confirm.sh
Continue? (y/n) No
Stopping
$ bash confirm.sh
Continue? (y/n) maybe
Please answer y or n

The script lowercases the answer once, so YES, Yes and yes all pass through the same comparison. The read command and its -p prompt option are the subject of lesson 31. Because the answer is stored in a variable and compared inside [[ ]], an empty answer, where the user just presses Enter, takes the final branch without any error.

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 Comparing Strings in Bash and get answers drawn from it.

Signed-in readers only.