Comparing Strings in Bash
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.