Log inSign up

Making decisions in Bash with if, elif, else and case

An if in Bash runs a command and takes the branch when that command exits with 0, so if grep -q deploy /etc/passwd; then ... fi is a complete condition. For comparisons use [[ ]]: [[ -f "$file" ]] for files, [[ "$a" == "$b" ]] for strings and (( n > 10 )) for numbers. When one value can match several patterns, a case block reads more cleanly than a chain of elif lines.

Topic: Bash scripting · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

How does an if statement decide what to run?

Bash looks only at the exit status of the command after if: zero means true, any other number means false. There is no separate boolean type. That makes it natural to branch directly on real commands:

if systemctl is-active --quiet nginx; then
  echo "nginx is running"
elif systemctl list-unit-files nginx.service >/dev/null 2>&1; then
  echo "nginx is installed but stopped"
else
  echo "nginx is not installed"
fi

The keywords then, elif, else and fi each need to start a new command, which is why the semicolon appears before then when it shares a line. Many tools have a quiet flag made for this style: grep -q, systemctl --quiet, id -u user with output thrown away. Since [[ ]] is itself just a command that exits 0 or 1, everything below follows the same rule.

Should I use [ ], [[ ]] or test?

In Bash scripts, prefer [[ ]]. The single bracket [ is an old command (identical to test) that works in every POSIX shell but splits unquoted variables and treats < as a redirection. The double bracket is a Bash keyword: it does not split words, supports && and || inside, allows pattern matching with == and regex matching with =~:

if [[ -n "$1" && "$1" != -* ]]; then
  echo "first argument looks like a name"
fi
[ "$a" = "$b" ]     # portable, quotes are mandatory
[[ $a == "$b" ]]    # Bash, left side safe even unquoted

Keep the spaces right after [[ and before ]]; without them Bash looks for a command named [[-n. Quoting the right side of == makes it a literal string; leaving it unquoted makes it a glob pattern.

Which tests check files and directories?

File tests take a single path and answer a yes or no question about it. The ones you will reach for on a server:

  • -e exists, -f regular file, -d directory, -L symbolic link
  • -r, -w, -x readable, writable, executable by the current user
  • -s exists and is not empty
  • file1 -nt file2 file1 is newer than file2
conf="/etc/myapp/app.conf"
if [[ ! -f "$conf" ]]; then
  echo "missing $conf" >&2
  exit 1
fi
if [[ -d /var/www/app.example.net && -w /var/www/app.example.net ]]; then
  echo "web root ready"
fi
[[ app.conf -nt app.conf.bak ]] && echo "config changed since backup"

The exclamation mark negates any test. Run these as the user the script will really use, since -w as root is almost always true.

How do I compare strings and numbers?

Strings use ==, !=, -z (empty) and -n (not empty); integers are clearest inside (( )), which accepts the familiar symbols:

env_name="${APP_ENV:-dev}"
if [[ "$env_name" == "production" ]]; then
  echo "careful: live system"
fi
[[ -z "$token" ]] && echo "no token set"
load=$(cut -d" " -f1 /proc/loadavg)
cores=$(nproc)
if (( ${load%.*} >= cores )); then
  echo "load $load on $cores cores"
fi

Inside [[ ]] the symbols < and > compare strings alphabetically, which gives surprises like 10 being smaller than 9. For numbers in brackets use -eq, -ne, -lt, -le, -gt and -ge, or simply switch to (( )). Note that (( )) only handles integers, so the load average above is cut at the decimal point first.

How do I match patterns and regular expressions?

Use an unquoted glob on the right side of == for simple wildcards, and =~ for an extended regular expression. Captured groups land in the BASH_REMATCH array:

file="backup-2026-12-03.tar.gz"
[[ $file == *.tar.gz ]] && echo "compressed archive"
re='^backup-([0-9]{4})-([0-9]{2})-([0-9]{2})'
if [[ $file =~ $re ]]; then
  echo "year ${BASH_REMATCH[1]}, month ${BASH_REMATCH[2]}"
fi
ip="198.51.100.24"
[[ $ip =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && echo "looks like IPv4"

Storing the regex in a variable first, as with re above, avoids quoting trouble with spaces and special characters. Do not put quotes around the variable on the right of =~, or Bash treats it as a plain string.

When is case better than if and elif?

Choose case whenever you compare one value against several fixed options or glob patterns, such as subcommands of a script. Each pattern ends with ), each branch ends with ;;, and the block closes with esac:

#!/usr/bin/env bash
case "${1:-}" in
  start|up)
    sudo systemctl start myapp ;;
  stop|down)
    sudo systemctl stop myapp ;;
  status)
    systemctl status myapp --no-pager ;;
  *.conf)
    echo "loading config file $1" ;;
  ""|-h|--help)
    echo "usage: ${0##*/} start|stop|status" ;;
  *)
    echo "unknown command: $1" >&2
    exit 2 ;;
esac

Patterns are tried top to bottom and the first match wins, so keep the catch all *) last. The pipe joins alternatives. Bash also offers ;& (fall through into the next branch) and ;;& (keep testing further patterns), but plain ;; covers nearly every real script.

Are there shorter ways to write simple conditions?

Yes, && runs the next command only on success and || only on failure, which suits one line guards:

[[ $EUID -eq 0 ]] || { echo "run with sudo" >&2; exit 1; }
command -v rsync >/dev/null || sudo apt install -y rsync
mkdir -p /srv/data && cd /srv/data

The braces group several commands; note the required space after { and the semicolon before }. Be careful with the pattern a && b || c: it is not an if/else, because c also runs when b fails. When both outcomes matter, write a full if. On Rocky and Alma replace the apt line with sudo dnf install -y rsync.

How do I debug a condition that never matches?

Trace it with bash -x or set set -x just before the test. The trace shows the values Bash actually compared, which usually exposes the problem at once:

set -x
[[ "$status" == "ok" ]] && echo yes
set +x

Typical causes: a trailing newline or carriage return captured from a file (remove it with ${status%$'\r'}), different letter case (compare ${status,,}), a missing space inside the brackets, or a number compared as a string. When a condition depends on a command, print its exit code with echo $? straight after running it by hand. Error handling with set -e interacts with conditions too, explained in Error handling with set -euo pipefail and trap.

Questions about if, else and case in Bash

Why does my script fail with unary operator expected?

An unquoted empty variable inside [ ] disappears and leaves the test broken. Quote it, as in [ "$x" = yes ], or switch to [[ ]].

Can I combine several conditions?

Yes. Inside [[ ]] use &&, || and parentheses for grouping, for example [[ -f $a && ( -r $a || $force == 1 ) ]].

Is case sensitive to upper and lower case?

Yes. Lowercase the value first with case "${1,,}" in, or turn on shopt -s nocasematch for the block.

How do I check whether a user or package exists?

Use the tool's own exit code: id deploy &>/dev/null for users, dpkg -s nginx &>/dev/null on Ubuntu and Debian or rpm -q nginx &>/dev/null on Rocky and Alma for packages.

Do I need fi after every if?

Yes, one fi closes each if, however many elif branches it has. Nested ifs each need their own.