Cloud VPS from $1.98/mo · pay with Bitcoin, Ethereum, Monero, USDT or Solana · paid in crypto
Linux

Bash if statements with [ ], [[ ]], (( )) and case

How Bash decides true and false, when to use [ ], [[ ]] or (( )), the string, number and file checks server scripts need, and the quoting traps that bite.

CloudSat teamNovember 18, 20268 min read
A path drawn in neon lines that forks into two glowing routes, one marked with a check and one with a cross.
On this pageif runs a command

Bash's if does not evaluate expressions the way most programming languages do. It runs a command and branches on that command's exit status: 0 means success, which counts as true, and anything else counts as false. [, [[ and (( are simply commands or keywords that produce an exit status. Once that idea clicks, the syntax and most of its traps make sense.

if runs a command

if sudo sshd -T | grep -qi '^permitrootlogin no'; then
  echo "root login is disabled"
else
  echo "root login is allowed in some form"
fi

sshd -T prints the effective SSH configuration, and grep -q exits with 0 when it finds a match. For a pipeline, if looks at the status of the last command, grep here. No brackets are involved, because none are needed.

Any command works as a condition. if ping -c 1 -W 2 203.0.113.10 >/dev/null; then checks reachability, and if command -v docker >/dev/null 2>&1; then checks that a program is installed. The special variable $? holds the status of the previous command, and the true and false commands return 0 and 1. The full form is if ...; then ...; elif ...; then ...; else ...; fi; the semicolons can be newlines.

You often want a command's output and its success at the same time. An assignment from command substitution returns the exit status of the command inside it, so one line can do both:

if ! body=$(curl -fsS --max-time 5 http://127.0.0.1:8080/health); then
  echo "health check failed" >&2
  exit 1
fi
echo "service says: $body"

curl -f turns HTTP errors such as 404 or 503 into a non-zero status, which is what makes the test meaningful. Without it, curl reports success for any response it manages to receive.

[ ], [[ ]] and (( )) compared

Form What it is Best for Works in plain sh
[ ... ] or test ... a builtin command portable scripts yes
[[ ... ]] a Bash keyword strings, patterns, regex, files no
(( ... )) arithmetic evaluation integer comparisons no

Because [ is an ordinary command, its arguments go through word splitting and globbing first, so an unquoted empty variable simply disappears and the test breaks. [[ is parsed by Bash itself: variables are not split or globbed, && and || work inside, == matches patterns and =~ matches regular expressions. (( )) evaluates arithmetic and returns true when the result is not zero. Inside it, variables do not even need a $.

Comparing strings

if [[ -z $1 ]]; then echo "no argument given"; fi
if [[ -n $1 ]]; then echo "argument is $1"; fi
if [[ $1 == "admin" ]]; then echo "exact match"; fi
if [[ $1 == *.log ]]; then echo "ends in .log"; fi
if [[ $1 == "*.log" ]]; then echo "is literally *.log"; fi

The last two lines show a detail worth remembering: on the right side of ==, an unquoted pattern matches like a file glob, while a quoted one is compared literally.

For anything more complex, =~ applies an extended regular expression and stores the capture groups in the BASH_REMATCH array:

version=$(nginx -v 2>&1)    # for example: nginx version: nginx/1.26.3
if [[ $version =~ nginx/([0-9]+)\.([0-9]+) ]]; then
  echo "major ${BASH_REMATCH[1]}, minor ${BASH_REMATCH[2]}"
fi

Leave the regex unquoted, since quoting turns it into a literal string. For long expressions, store the pattern in a variable first (re='^[0-9]+$') and write [[ $input =~ $re ]].

Comparing numbers

Inside [ ] and [[ ]], numbers use letter operators: -eq, -ne, -lt, -le, -gt and -ge. Inside (( )) you write ordinary math operators.

count=$(find /var/backups -name '*.tar.gz' -mtime -1 | wc -l)
if (( count == 0 )); then
  echo "no backup in the last 24 hours"
elif [[ $count -gt 3 ]]; then
  echo "more backups than expected: $count"
fi

Two classic traps live here. In [[ ]], the < and > operators compare strings, so [[ 10 < 9 ]] is true because "1" sorts before "9". In [ ] it is worse: [ 10 > 9 ] is parsed as a redirection, creates a file named 9 and returns true.

Bash arithmetic is integer-only, so (( 3 / 2 )) evaluates to 1. To compare decimals, such as load averages, hand the job to awk, which exits with 0 when the condition holds:

load=$(cut -d ' ' -f1 /proc/loadavg)
if awk -v l="$load" 'BEGIN { exit !(l > 4.0) }'; then
  echo "load is high: $load"
fi

Testing files

Test True when the path
-e path exists, whatever its type
-f path is a regular file
-d path is a directory
-L path is a symbolic link
-s path exists and is not empty
-r, -w, -x path is readable, writable, executable by you
a -nt b a was modified more recently than b
config=/etc/myapp/config.yml
if [[ ! -f $config ]]; then
  echo "missing $config" >&2
  exit 1
fi
if [[ $config -nt /run/myapp.reloaded ]]; then
  systemctl reload myapp && touch /run/myapp.reloaded
fi

! negates any test. The second block reloads a service only when its configuration changed since the last reload, a pattern that keeps cron jobs cheap.

Combining conditions

Inside [[ ]], join tests with && and ||. With the portable [ ], write separate tests joined by the shell's own && and ||, and leave the old -a and -o operators alone: POSIX marks them obsolescent because they parse ambiguously.

if [[ -f $config && -r $config ]]; then echo "readable config"; fi
if [ -f "$config" ] && [ -r "$config" ]; then echo "same test, portable"; fi
if ! systemctl is-active --quiet nginx; then echo "nginx is down"; fi

Short guards at the top of a script read well as one-liners:

command -v rsync >/dev/null || { echo "rsync is not installed" >&2; exit 1; }
[[ $EUID -eq 0 ]] || { echo "run this as root" >&2; exit 1; }

Avoid using a && b || c as a compact if-else. If b fails, c runs as well, which is rarely what you meant.

case for many branches

When one value decides between several paths, case is clearer than a ladder of elif lines. Each pattern is a glob, the first match wins and ;; ends a branch.

case $1 in
  start|stop|restart)
    systemctl "$1" myapp
    ;;
  status)
    systemctl status myapp --no-pager
    ;;
  *.conf)
    echo "checking config file $1"
    ;;
  *)
    echo "usage: $0 start|stop|restart|status" >&2
    exit 2
    ;;
esac

Two refinements help in larger scripts. Ending a branch with ;& falls through into the next branch's commands, and ;;& keeps testing the remaining patterns instead of stopping at the first match. For case-insensitive matching, run shopt -s nocasematch before the case block, so START and Start take the same branch as start.

Traps worth memorizing

  1. Spaces are mandatory. [$a = b] fails with "command not found", because [ is a word like any other command.
  2. Quote variables inside [ ]. If $name is empty, [ $name = admin ] becomes [ = admin ] and Bash complains about a unary operator. [[ ]] does not need the quotes.
  3. Text and numbers use different operators. = and == compare strings; -eq compares integers.
  4. Leading zeros mean octal in (( )) and in [[ ]] number tests. month=$(date +%m) returns 08 in August, and (( month > 6 )) then fails with "value too great for base". Force decimal with (( 10#$month > 6 )).
  5. [[ does not exist in sh. On Debian and Ubuntu, /bin/sh is dash, so a script run with sh script.sh fails with [[: not found. Start scripts with #!/usr/bin/env bash and run them directly.
  6. set -e does not stop the script when a command fails inside an if condition or a && chain. That is by design, not a bug.
  7. if [ $(some_command) ] tests the command's output text. To test whether it succeeded, write if some_command; then.

A preflight check that uses all of it

This script runs before a deploy and stops at the first problem. The fail helper is a small function, the subject of writing Bash functions.

#!/usr/bin/env bash
set -u

fail() { echo "preflight: $*" >&2; exit 1; }

(( EUID == 0 )) || fail "run as root"
command -v nginx >/dev/null || fail "nginx is not installed"

free_kb=$(df --output=avail / | tail -n 1)
(( free_kb > 1048576 )) || fail "less than 1 GB free on /"

nginx -t 2>/dev/null || fail "nginx configuration test failed"

if systemctl is-active --quiet nginx; then
  systemctl reload nginx
else
  systemctl start nginx
fi
echo "preflight passed"

FAQ

Should I use [ ] or [[ ]]?

In scripts that start with #!/usr/bin/env bash, use [[ ]] for strings and files and (( )) for numbers. Keep [ ] for scripts that must run under plain sh, such as some container entrypoints and minimal init scripts.

Why does Bash say 10 is less than 9?

Inside [[ ]], < compares strings character by character, and "1" sorts before "9". Use -lt, or compare inside (( )).

Why does my condition pass even when the value is "false"?

With a single argument, [ "$ENABLED" ] only checks that the string is not empty, so the text false passes as easily as true. Bash has no boolean type for variables. Compare the value explicitly, as in [[ $ENABLED == true ]], or store 0 and 1 and test them with (( ENABLED )).

How do I check whether a variable is set at all?

[[ -v NAME ]] is true when NAME is set, even to an empty string, whereas [[ -z $NAME ]] cannot tell unset from empty. Under set -u, reading an unset variable is an error, so test with -v first or read it with a default such as ${NAME:-}.

Run it on CloudSat. Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. See plans or deploy a server.