Coding

Bash If Statement: Syntax, Operators and Examples

A bash if statement runs a command and executes the then block when that command exits with status 0. The basic form is if [ condition ]; then ... fi, with optional elif and else branches.

#!/usr/bin/env bash
count=5

if [ "$count" -gt 3 ]; then
  echo "more than 3"
elif [ "$count" -eq 3 ]; then
  echo "exactly 3"
else
  echo "3 or fewer"
fi

Example output: more than 3. The same structure is used everywhere below; only the test changes.

Bash if statement syntax

The bash manual gives the grammar as if list; then list; [ elif list; then list; ] ... [ else list; ] fi. Three things follow from it:

  • The condition is a command, not a special expression. [ ... ] is simply a command (a synonym for test) that sets an exit status.
  • then must start a new command. Either put it on its own line or put ; before it, as in if [ -f "$f" ]; then.
  • fi (if backwards) closes the block. Forgetting it gives a syntax error that points to the end of the file.

The exit status of the whole if is, per the manual, "the exit status of the last command executed, or zero if no condition tested true". So an if with no matching branch and no else still succeeds, which matters under set -e.

Single brackets [ ] vs double brackets [[ ]]

[ ] works in every POSIX shell. [[ ]] is a bash keyword with extra features, and it fails in dash, which is /bin/sh on Debian and Ubuntu.

Feature[ ][[ ]]
Works in shYesNo, bash and similar shells only
Word splitting of variablesYes, so you must quote themNo, per the manual "words between the [[ and ]] do not undergo word splitting and pathname expansion"
Pattern match: == *.logNoYes
Regex: =~NoYes (POSIX extended regular expression)
Combine tests-a, -o, or separate [ ] joined by &&&& and || inside the brackets

Use [[ ]] in scripts that start with #!/usr/bin/env bash. Use [ ] when the script must run under plain sh. Still quote variables in both: it is harmless in [[ ]] and required in [ ].

File tests

These operators are from the "Conditional Expressions" section of the bash manual:

TestTrue if
-e filefile exists
-f filefile exists and is a regular file
-d filefile exists and is a directory
-r filefile exists and is readable
-w filefile exists and is writable
-x filefile exists and is executable
-s filefile exists and has a size greater than zero
config="$HOME/.myapp.conf"

if [ -f "$config" ]; then
  echo "loading $config"
elif [ -d "$config" ]; then
  echo "$config is a directory, expected a file" >&2
else
  echo "no config found, using defaults"
fi

Put ! in front of a test to negate it: if [ ! -d "$dir" ]; then mkdir "$dir"; fi.

String tests

TestTrue if
-z "$s"the string has length zero
-n "$s"the string has non-zero length
"$a" = "$b"the strings are equal
"$a" != "$b"the strings are not equal
answer="yes"

if [ "$answer" = "yes" ]; then
  echo "confirmed"
fi

if [ -z "$1" ]; then
  echo "usage: $0 <name>" >&2
  exit 1
fi

With [ ], write a single =. The manual says "= should be used with the test command for POSIX conformance". In [[ ]], = and == are the same.

Pattern and regex matching with [[ ]]

In [[ ]] the right side of == is a pattern, so wildcards work. Quote the right side to compare literally; the manual says any quoted part of the pattern matches literally.

file="server.log"

if [[ $file == *.log ]]; then
  echo "a log file"
fi

if [[ $file == "*.log" ]]; then
  echo "only a file literally named *.log"
fi

Example output: a log file. The second test is false for server.log, so it prints nothing.

For =~ the right side is a POSIX extended regular expression. The manual notes it succeeds if the pattern matches any part of the string, so anchor it with ^ and $ to match the whole value:

version="v2.14"

if [[ $version =~ ^v[0-9]+\.[0-9]+$ ]]; then
  echo "looks like a version tag"
fi

Keep the regex in the test unquoted, or store it in a variable first (re='^v[0-9]+\.[0-9]+$', then [[ $version =~ $re ]]). Quoting it makes bash treat it as a literal string in recent versions.

Number tests

Compare integers with -eq, -ne, -lt, -le, -gt and -ge:

if [ "$count" -ge 10 ]; then
  echo "ten or more"
fi

Bash also has an arithmetic form, (( )), which reads like other languages and needs no $ on variable names:

if (( count > 2 && count < 10 )); then
  echo "between 3 and 9"
fi

Do not write [ "$count" > 2 ]. In single brackets > is output redirection, so bash creates a file named 2 and the test succeeds whenever the string is non-empty. In [[ ]], < and > compare strings, "lexicographically using the current locale" according to the manual, so [[ 10 > 9 ]] is false. For numbers use -gt or (( )).

Combine conditions: AND, OR, NOT

# [[ ]]: && and || inside the brackets
if [[ -f "$f" && -r "$f" ]]; then
  echo "readable file"
fi

# [ ]: join separate tests with the shell operators
if [ -f "$f" ] && [ -r "$f" ]; then
  echo "readable file"
fi

if [ "$env" = "dev" ] || [ "$env" = "test" ]; then
  echo "non-production"
fi

Both && and || short-circuit: the right side is skipped when the left side already decides the result. Prefer separate [ ] tests over -a and -o inside one bracket, because those two operators become ambiguous with some arguments.

Use a command as the condition

Because if tests an exit status, you can put any command after it. No brackets are needed:

if grep -q "ERROR" app.log; then
  echo "errors found"
fi

if ! command -v git >/dev/null 2>&1; then
  echo "git is not installed" >&2
  exit 1
fi

if mkdir "$dir" 2>/dev/null; then
  echo "created $dir"
else
  echo "could not create $dir" >&2
fi

grep -q prints nothing and exits 0 on a match. A command's exit status is stored in $?, but testing the command directly, as above, is shorter and avoids overwriting $? by accident.

One-line if and shortcuts

An if fits on one line when each part is separated by ;:

if [ -f notes.txt ]; then echo "found"; else echo "missing"; fi

For a single action, && and || are shorter:

[ -d "$dir" ] || mkdir "$dir"
[ -f "$f" ] && echo "exists"

Do not chain A && B || C as a replacement for if/else. If B fails, C runs too, even though A was true. Use a real if when there are two outcomes.

Common mistakes

  • Missing spaces. [$a=$b] and if [ "$a" = "$b"] fail because [ and ] are separate words. Put a space after [ and before ].
  • Unquoted variables in [ ]. If name is empty or contains a space, [ $name = "bob" ] expands into the wrong number of arguments and fails with a test error. Write [ "$name" = "bob" ]. See bash script basics for a real example of this error.
  • Spaces around the assignment. x = 5 runs a command named x. Assign with x=5.
  • Using = for numbers. [ "10" = "10.0" ] compares text and is false. Use -eq for integers. Bash arithmetic does not handle decimals; use bc or awk for those.
  • Missing then or fi. Each if needs its own then and its own fi. Each elif needs a then.
  • Empty branches. A then block with no command is a syntax error. Use the no-op : as a placeholder.

If your if statement still misbehaves

Run the script with bash -x script.sh. Bash prints each command after expansion, prefixed with +, so you can see exactly what arguments [ received. To check a condition by hand, run it alone and print the status:

[ -f "$file" ]; echo $?

A 0 means true and 1 means false. If the script works in your terminal but not as sh script.sh, you probably used [[ ]] or == patterns, which need bash. For looping over files and testing each one, see bash for loop examples.

Frequently asked questions

Do I need spaces inside the brackets of a bash if statement?
Yes. In [ "$a" = "$b" ], the opening bracket is a command named [ and the closing ] is its last argument, so each needs a space on both sides. Writing ["$a"="$b"] makes bash look for a command with that odd name.
What is the difference between = and == in bash?
Inside [ ], use a single = for string equality, because the bash manual says = should be used with the test command for POSIX conformance. Inside [[ ]], both mean string equality, and the right-hand side is treated as a pattern unless you quote it.
How do I compare numbers in a bash if statement?
Use -eq, -ne, -lt, -le, -gt and -ge inside [ ] or [[ ]], or put the comparison in (( )), for example if (( count > 2 )). Do not use > inside single [ ]: it is a redirection there, not a comparison.
Can an if statement run a command instead of a test?
Yes. if takes any command as its condition and runs the then branch when that command exits with status 0. That is why if grep -q pattern file.txt; then works with no brackets at all.

Sources