Testing Conditions with test and [ ]
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:
0when the expression is true,1when the expression is false,2when 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:
| Expression | True 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:
| Operator | Meaning |
|---|---|
-eq | equal |
-ne | not equal |
-lt | less than |
-le | less than or equal |
-gt | greater than |
-ge | greater 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:
| Expression | True when |
|---|---|
-e path | the path exists, of any type |
-f path | it is a regular file |
-d path | it is a directory |
-s path | it exists and has a size greater than zero |
-r path | it is readable by you |
-w path | it is writable by you |
-x path | it 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.