Common Conditional Statement Mistakes
Conditional statements look simple, yet a handful of small slips cause most of the confusing behavior in Bash scripts. Some of them stop the script with an error message that does not mention the real cause. Others are worse, because they produce no error at all and quietly make a test always true or always false. This lesson walks through each slip, shows exactly what Bash prints, and explains the rule that was broken. Every example was run with Bash 5.2, and the messages are shown as the shell printed them for a script file, with the script name and line number at the front.
Missing Spaces Around the Brackets
The opening bracket [ is a command, not punctuation, and the closing bracket ] is its last argument. Both need a space on each side. If the space after [ is missing, Bash reads the first word as a different command name:
#!/usr/bin/env bash
x=5
if [$x = 5]; then
echo "equal"
fi
Output:
spaces.sh: line 3: [5: command not found
After expansion, [$x became the word [5, and there is no command with that name. Because the command failed with status 127, the if treated the condition as false and skipped the body.
A missing space around the = is quieter and more dangerous. When the whole comparison is one word, the test has a single argument, and a single non-empty argument is always true (lesson 68):
x=5
if [ $x=7 ]; then
echo "[ \$x=7 ] is true even though x is 5"
fi
if [ "$x" = 7 ]; then
echo "wrong"
else
echo "[ \"\$x\" = 7 ] is false, as expected"
fi
Output:
[ $x=7 ] is true even though x is 5
[ "$x" = 7 ] is false, as expected
The text 5=7 is a single non-empty string, so [ 5=7 ] succeeds. Write the operands and the operator as three separate words.
Unquoted Variables That Are Empty or Contain Spaces
Inside [ ], an unquoted variable is subject to word splitting. An empty variable disappears completely, and a value with spaces becomes several words:
name=""
if [ $name = "ana" ]; then
echo "hello ana"
else
echo "not ana"
fi
name="Ana Maria"
if [ $name = "Ana Maria" ]; then
echo "match"
else
echo "no match"
fi
Output:
unquoted.sh: line 3: [: =: unary operator expected
not ana
unquoted.sh: line 9: [: too many arguments
no match
In the first test the empty variable vanished, so [ saw = ana and tried to treat = as a unary operator. In the second, Ana Maria split into two words, giving [ four arguments where it expected three. Both tests also evaluated as false, so the script carried on and printed a wrong answer after the error. Quoting the variable keeps it as exactly one argument:
name=""
if [ "$name" = "ana" ]; then
echo "hello ana"
else
echo "quoted: not ana, no error"
fi
Output:
quoted: not ana, no error
A related slip is [ -n $v ] with an empty variable. With the quotes missing, the test becomes [ -n ], which has one argument and is true:
unset v
if [ -n $v ]; then echo "[ -n \$v ] with an empty variable is true"; fi
if [ -n "$v" ]; then echo yes; else echo "[ -n \"\$v\" ] is false"; fi
Output:
[ -n $v ] with an empty variable is true
[ -n "$v" ] is false
Lessons 53 and 55 explain word splitting and quoting in detail. Inside [[ ]] (lesson 69) this particular problem does not occur, because that construct does not split words.
Comparing Numbers as Text and Text as Numbers
The operators = and != compare text. The operators -eq, -ne, -lt, -le, -gt and -ge compare integers. Using the wrong family gives wrong answers or errors:
a=10
b=010
if [ "$a" = "$b" ]; then echo "= says equal"; else echo "= says different (text 10 vs 010)"; fi
if [ "$a" -eq "$b" ]; then echo "-eq says 10 and 010 are equal"; fi
if [ abc -eq 1 ]; then echo "eq"; else echo "abc -eq 1 failed"; fi
Output:
= says different (text 10 vs 010)
-eq says 10 and 010 are equal
[: abc: integer expression expected
abc -eq 1 failed
The strings 10 and 010 are different text but the same number. When -eq receives something that is not an integer, [ prints integer expression expected and returns status 2, which an if treats as false.
Decimal Numbers Are Not Integers
The integer operators accept only whole numbers. A value such as 1.5 produces the same error, and the arithmetic form (( )) rejects it as well:
if [ 1.5 -gt 1 ]; then echo "gt"; else echo "1.5 -gt 1 failed"; fi
if (( 1.5 > 1 )); then echo yes; fi
Output:
[: 1.5: integer expression expected
1.5 -gt 1 failed
float.sh: line 2: ((: 1.5 > 1 : syntax error: invalid arithmetic operator (error token is ".5 > 1 ")
Bash has no floating-point arithmetic. For decimal comparisons, hand the work to a tool that has it, such as awk or bc:
price=1.5
if awk -v p="$price" 'BEGIN { exit !(p > 1) }'; then
echo "awk: $price is greater than 1"
fi
echo "bc prints: $(echo "$price > 1" | bc -l)"
Output:
awk: 1.5 is greater than 1
bc prints: 1
The awk program exits with status 0 when the comparison is true, so it can be used directly as the condition. The bc tool prints 1 for true and 0 for false, which a script can then test as text or as an integer. On a minimal system bc may not be installed.
Using > and < Inside [ ]
Inside single brackets, > and < are still redirection operators. The shell removes them, together with the word that follows, before [ ever runs. The result is that [ 5 > 10 ] creates a file named 10:
#!/usr/bin/env bash
cd "$(mktemp -d)"
ls
if [ 5 > 10 ]; then echo "5 > 10 is true?"; fi
ls
echo "file 10 now exists; content size: $(wc -c < 10)"
Output:
5 > 10 is true?
10
file 10 now exists; content size: 0
The first ls printed nothing because the folder was empty. After the test, a new empty file 10 exists, and the test itself became [ 5 ], which is true. The condition was true, and the script also left a stray file behind.
Use the named integer operators, or use (( )), which treats > as a comparison:
if [ 5 -gt 10 ]; then echo "yes"; else echo "5 -gt 10 is false"; fi
if (( 5 > 10 )); then echo "yes"; else echo "(( 5 > 10 )) is false"; fi
Output:
5 -gt 10 is false
(( 5 > 10 )) is false
Inside [[ ]] the symbols are comparison operators, but they compare text, character by character. For that reason [[ 5 > 10 ]] is true, because the character 5 sorts after the character 1. This is why [[ 5 > 10 ]] is not a numeric test either. Lesson 73 covers integer comparisons properly.
Putting && and || Inside [ ]
The operators && and || belong to the shell, not to [. They end the command, so the bracket test is cut in half:
touch a.txt b.txt
if [ -f a.txt && -f b.txt ]; then
echo "both"
fi
echo "next line runs"
Output:
andinside.sh: line 3: [: missing `]'
next line runs
The shell split the line at &&. The first half, [ -f a.txt, has no closing bracket, and the second half was never run as part of that test. Use two separate tests joined by the shell operator, or one [[ ]] test, which understands && and || itself:
if [ -f a.txt ] && [ -f b.txt ]; then echo "both exist (two tests)"; fi
if [[ -f a.txt && -f b.txt ]]; then echo "both exist ([[ ]])"; fi
Output:
both exist (two tests)
both exist ([[ ]])
Inside single brackets, the old operators -a and -o also exist, but they are ambiguous in some cases, and the two-test form above is clearer (lesson 74).
Testing a Command with [ ] or $( )
The condition of an if is a command, and the if looks at its exit status. Brackets are only needed when the thing being tested is a string, a number or a file. To test whether a command succeeded, just run it. Wrapping it in brackets makes [ treat the command name as one of its own arguments:
printf 'alpha\nbeta\n' > words.txt
if [ grep -q beta words.txt ]; then
echo "found"
fi
Output:
cmdsub.sh: line 3: [: syntax error: `-q' unexpected
Wrapping the command in $( ) is another trap. The text that the command prints is then run as a new command:
if $(grep beta words.txt); then
echo "found"
else
echo "else branch ran"
fi
Output:
cmdsub2.sh: line 3: beta: command not found
else branch ran
The grep printed the line beta, and Bash tried to execute beta. The correct form uses the command directly, with -q to keep it quiet. When the output itself is needed, capture it and test the captured text:
if grep -q beta words.txt; then echo "grep -q directly: found"; fi
x=$(grep beta words.txt)
if [ -n "$x" ]; then echo "capturing output: found $x"; fi
Output:
grep -q directly: found
capturing output: found beta
Mixing Up True, False and the Words "true" and "false"
Success and failure are decided by exit statuses, and 0 means success (lesson 66). Text that merely looks like a boolean has no special meaning to [ ]. Any non-empty string is true:
flag="false"
if [ "$flag" ]; then echo "[ \"false\" ] is true: non-empty string"; fi
flag="0"
if [ "$flag" ]; then echo "[ \"0\" ] is true: non-empty string"; fi
flag=""
if [ "$flag" ]; then echo "yes"; else echo "[ \"\" ] is false: empty string"; fi
Output:
[ "false" ] is true: non-empty string
[ "0" ] is true: non-empty string
[ "" ] is false: empty string
The arithmetic form (( )) works the other way around: it treats the number 0 as false and every other number as true:
if (( 0 )); then echo "yes"; else echo "(( 0 )) is false"; fi
if (( 1 )); then echo "(( 1 )) is true"; fi
Output:
(( 0 )) is false
(( 1 )) is true
Because (( )) reverses the usual convention for the number 0, it can feel inconsistent. The reason is that it reports success when its result is non-zero. Keep the two ideas apart: exit status 0 is success, and the number 0 is false inside (( )).
A flag variable can hold the words true and false and then be run as a command, since both words are also commands. The text can also be compared explicitly:
flag=false
if $flag; then echo "yes"; else echo "running the word false as a command fails"; fi
flag=true
if $flag; then echo "running the word true as a command succeeds"; fi
if [ "$flag" = true ]; then echo "comparing text works too"; fi
Output:
running the word false as a command fails
running the word true as a command succeeds
comparing text works too
Running the variable works only when it always holds one of those two words. Comparing the text with = is more forgiving, because an unexpected value simply gives a false result instead of running an unknown command.
Assigning When You Meant to Compare
Inside (( )), a single = is an assignment, and the value of the assignment becomes the result of the test:
x=1
if (( x = 5 )); then echo "assignment: x is now $x and the test is true"; fi
if (( x = 0 )); then echo "yes"; else echo "assigning 0 makes the test false, x is $x"; fi
Output:
assignment: x is now 5 and the test is true
assigning 0 makes the test false, x is 0
The variable was changed twice, and the test succeeded or failed based on the value that was assigned. Use == for comparison:
x=1
if (( x == 5 )); then echo "yes"; else echo "comparison: x is still $x"; fi
Output:
comparison: x is still 1
Inside [ ] the equivalent slip does not assign anything. A single = there is the text-comparison operator, so the test is correct and simply reports the truth:
x=1
if [ "$x" = 5 ]; then echo yes; else echo "[ \"\$x\" = 5 ] false"; fi
Output:
[ "$x" = 5 ] false
Checking $? at the Wrong Time
The special parameter $? holds the status of the most recent command. Any command run in between replaces it, including a harmless echo:
grep -q needle /dev/null
echo "searched"
if [ $? -eq 0 ]; then
echo "found (wrong: this is the status of echo)"
else
echo "not found"
fi
Output:
searched
found (wrong: this is the status of echo)
The grep failed with status 1, but the echo that followed succeeded and reset $? to 0. Test the command directly in the if, or copy the status into a variable on the very next line:
grep -q needle /dev/null
status=$?
echo "searched"
if [ "$status" -eq 0 ]; then echo "found"; else echo "not found (status $status saved first)"; fi
if grep -q needle /dev/null; then echo "found"; else echo "not found (direct if)"; fi
Output:
searched
not found (status 1 saved first)
not found (direct if)
Lesson 117 covers $? in more detail.
Structure Slips: then, fi and else if
A missing ; or newline before then makes Bash read then as an argument to the test, and the error is reported much later, at the fi:
n=3
if [ "$n" -gt 2 ] then
echo "big"
fi
Output:
nothen.sh: line 5: syntax error near unexpected token `fi'
A missing fi is reported at the end of the file, where Bash realizes that the statement never closed:
n=3
if [ "$n" -gt 2 ]; then
echo "big"
echo "done"
Output:
nofi.sh: line 6: syntax error: unexpected end of file
Writing else if instead of elif opens a second if inside the else, and that inner if needs its own fi. With only one fi, the outer statement stays open and the same end-of-file error appears:
n=1
if [ "$n" -gt 2 ]; then
echo "big"
else if [ "$n" -gt 0 ]; then
echo "small"
fi
echo "end"
Output:
elseif.sh: line 9: syntax error: unexpected end of file
Use elif for a chain of conditions (lesson 67). These errors point at the end of the file, so look for the if that was never closed rather than the reported line itself.
Windows Line Endings
A script saved with Windows line endings ends every line with a carriage return character (\r) in addition to the newline. Bash treats that character as part of the last word of the line, which breaks keywords such as then and fi. The result is an error message that does not seem to refer to anything in the file:
bash crlf.sh
Output:
crlf.sh: line 6: syntax error: unexpected end of file
If the script is started directly with ./crlf.sh, the carriage return becomes part of the interpreter name in the first line:
/usr/bin/env: 'bash\r': No such file or directory
The od -c tool shows the hidden characters, and a grep for the carriage return counts the affected lines:
head -n 2 crlf.sh | od -c
grep -c $'\r' crlf.sh
Output:
0000000 # ! / u s r / b i n / e n v b
0000020 a s h \r \n x = 5 \r \n
0000032
5
Removing the carriage returns repairs the file:
tr -d '\r' < crlf.sh > fixed.sh
grep -c $'\r' fixed.sh
bash fixed.sh
Output:
0
five
The grep -c count is 0 for the repaired copy, and the script prints five. Many editors have a setting for the line-ending style. Choose Unix line endings (LF) for any file that Bash will read.
Using == with [ ] in Scripts for sh
Bash accepts == inside single brackets as a synonym for =, but the POSIX standard defines only =. A script with the #!/bin/sh line that runs under Dash fails:
#!/bin/sh
a=x
if [ "$a" == "x" ]; then echo "equal"; else echo "not equal"; fi
if [ "$a" = "x" ]; then echo "single = works"; fi
Output in Dash:
dashdouble.sh: 3: [: x: unexpected operator
not equal
single = works
Under Bash, the same file prints equal and single = works. Using a single = inside [ ] behaves the same everywhere, so it is the safe choice for scripts that must be portable (lessons 188 and 189).