Short answer: bash writes if else as if CONDITION; then ...; elif CONDITION; then ...; else ...; fi. The condition is any command, and exit status 0 counts as true; most scripts use a test in [[ ]] or [ ], or arithmetic in (( )), with spaces inside the brackets.
#!/bin/bash
load=${1:-0}
if (( load > 90 )); then
echo "critical"
elif (( load > 70 )); then
echo "warning"
else
echo "ok"
fi$ bash load.sh 95
critical
$ bash load.sh 75
warning
$ bash load.sh 10
okEvery example and error message in this guide was run with bash 5.2.15, the version in Debian 12, in a scratch folder; the operators are those of the Bash Reference Manual.
if, then, elif, else, fi: the syntax
then must start a new line or follow a ;, every if needs its own fi, and elif and else are optional. Because the condition is a command, you can test the result of grep, id or command -v directly, and ! turns the result around:
if grep -q "^root:" /etc/passwd; then
echo "root user exists"
fi
if id deploy &>/dev/null; then
echo "exists"
else
echo "no user deploy"
fi
if ! command -v rsync >/dev/null; then
echo "rsync is missing"
fiOn a server without a deploy account, the first two print root user exists and no user deploy. The brackets are commands too: type [ [[ answers [ is a shell builtin and [[ is a shell keyword. A test sets exit status 0 when it is true and 1 when it is false, and if only reads that number.
[ ] vs [[ ]] vs (( ))
| Form | What it is | Use it for | Watch out |
|---|---|---|---|
[ ... ] | The test builtin, POSIX | Scripts that must also run under sh (dash on Debian and Ubuntu) | Quote every variable; no patterns, no && inside |
[[ ... ]] | A bash keyword (also zsh and ksh) | Strings, patterns (==), regex (=~), files in bash scripts | Not in sh: dash prints [[: not found |
(( ... )) | Arithmetic evaluation | Numbers with < > == and math, variables without $ | Integers only; a result of 0 counts as false |
In a script that starts with #!/bin/bash, prefer [[ ]] for strings and files and (( )) for numbers. [[ ]] does not split variables on spaces, so an unquoted $file holding my file.txt still works there, while [ -f $file ] fails with [: my: binary operator expected. Use [ ] when the script has to run under plain sh.
String, number and file tests
| Test | True when | Example |
|---|---|---|
-z STR / -n STR | The string is empty / not empty | [[ -z $var ]] |
A == B / A != B | Strings equal / differ; in [ ] under sh use a single = | [ "$env" = "prod" ] |
A == pattern | Glob match, only in [[ ]] with the pattern unquoted | [[ $host == web-* ]] |
A =~ regex | Regex match, groups land in BASH_REMATCH | [[ $host =~ ^web-([0-9]+)$ ]] |
-eq -ne -lt -le -gt -ge | Integer compare in [ ] and [[ ]] | [ "$n" -ge 3 ] |
< <= > >= == | Integer compare inside (( )) | (( n >= 3 )) |
-e / -f / -d | Path exists / is a regular file / is a directory | [[ -d /srv/backup ]] |
-s / -L | File is not empty / is a symlink | [[ -s $log ]] |
-r / -w / -x | Readable / writable / executable by you | [[ -x ./deploy.sh ]] |
A -nt B | File A is newer than file B | [[ app.conf -nt app.conf.bak ]] |
$ name="web-01"
$ [[ $name == web-* ]] && echo "glob match"
glob match
$ [[ $name == "web-*" ]] && echo match || echo "quoted pattern: no match"
quoted pattern: no match
$ [[ $name =~ ^web-([0-9]+)$ ]] && echo "number ${BASH_REMATCH[1]}"
number 01
$ [[ 10 < 9 ]] && echo "10 < 9 as strings"
10 < 9 as strings
$ (( 10 < 9 )) || echo "(( 10 < 9 )) is false"
(( 10 < 9 )) is falseThat last pair is the classic number bug: inside [[ ]], < and > compare strings character by character, so 10 sorts before 9. For numbers use -lt and friends or (( )). One more trap: [[ $n -eq 0 ]] with n=abc is true without any error, because [[ ]] evaluates abc as an unset variable, which is 0. Check that input is numeric first, for example with [[ $n =~ ^[0-9]+$ ]].
&& and ||: combining conditions
if [[ $x -gt 1 && $x -lt 10 ]]; then echo "between"; fi # inside [[ ]]
if [ "$x" -gt 1 ] && [ "$x" -lt 10 ]; then echo "between"; fi # two [ ] tests
if [[ $env == prod || $env == staging ]]; then echo "remote"; fiOutside of if, && runs the next command only on success and || only on failure, which makes short checks read well: [ -d /srv/backup ] || mkdir -p /srv/backup. But A && B || C is not if else. C also runs when A succeeds and B fails:
$ true && false || echo "fallback ran although the first command succeeded"
fallback ran although the first command succeededUse the short form when B cannot fail, such as an echo, and a real if when it can.
if else on one line
if [ -f /etc/os-release ]; then echo yes; else echo no; fi
(( n % 2 == 0 )) && echo even || echo odd
used=$(df --output=pcent / | tail -n 1 | tr -dc '0-9'); if [ "$used" -gt 90 ]; then echo "root disk ${used}% full"; fiEach part ends with ; except the last. Two spots trip people up: no ; after then or else (else; echo b fails with syntax error near unexpected token `;'), and a ; is required before then and before fi. The disk check is a useful line for a cron job on a VPS; send its output somewhere you will read, as redirecting stdout and stderr explains.
Common bash if errors and their fixes
[: =: unary operator expected
e1.sh: line 3: [: =: unary operator expectedThe script had [ $status = "active" ]. An empty, unquoted variable disappears, and [ sees only = active. Quote it, [ "$status" = "active" ], or use [[ $status == active ]]. Note that bash carries on after this error and takes the else branch, so a broken test can hide in a script for a long time.
[: too many arguments
The opposite case: the variable held a b, split into two words, and [ got one argument too many. The fix is the same, double quotes or [[ ]]. With a file test it reads [: my: binary operator expected.
Missing spaces: [yes: command not found
[$x = "yes"] runs a command called [yes: bash: line 1: [yes: command not found. The brackets need a space on both sides. Without spaces around = there is no error at all, which is worse: [ "$x"="yes" ] is a single non-empty string and therefore always true. In our test it printed “matched” with x=no.
syntax error near unexpected token `fi'
e2.sh: line 4: syntax error near unexpected token `fi'
e2.sh: line 4: `fi'Line 2 of that script was if [ -f /etc/hostname ] then, without the ;, so bash never saw a then and the fi came as a surprise. The same message appears for an empty then block (put : there as a placeholder) and for an elif line without ; then.
syntax error: unexpected end of file
A fi is missing. The usual cause is else if instead of elif: that opens a second if that needs a second fi. Our seven-line test with else if failed with e5.sh: line 8: syntax error: unexpected end of file, a line past the end of the file. Windows line endings cause it too (a fi followed by a carriage return is not fi); the guide to running .sh files shows how to spot and fix them.
[[: not found and [: unexpected operator
Both mean the script ran under sh, which is dash on Debian and Ubuntu, not bash. sh e7.sh printed e7.sh: 2: [[: not found and, for [ $a == foo ], [: foo: unexpected operator. Run the script with bash or ./script.sh and a #!/bin/bash first line, or stick to [ ] with a single =.
if inside loops and on a server
if does most of its work inside loops: skip a host, stop at the first error, retry a download. The bash for loop guide has those patterns, with break and continue. When the same variable is compared with many values, case reads better than a long elif chain.
- Scripts started by cron or systemd do not read your shell startup files and get a shorter PATH, so a condition such as
command -v nodefor a Node.js installed with nvm can be false there while it is true in your SSH session; exit code 127 explains why. - Test a script with
bash -n script.sh(syntax check only) before you put it in a crontab on a production server.
Frequently asked
What is the syntax of if else in bash?
if CONDITION; then COMMANDS; elif CONDITION; then COMMANDS; else COMMANDS; fi. The condition is any command and counts as true when it exits with status 0. The then must follow a semicolon or a new line, elif and else are optional, and every if ends with its own fi.
What is the difference between [ ] and [[ ]] in bash?
[ ] is the POSIX test builtin and also works in sh, but it splits unquoted variables, so every variable needs double quotes. [[ ]] is a bash keyword that does not split variables and adds glob patterns with == and regular expressions with =~. In a script that starts with #!/bin/bash, [[ ]] is the safer choice.
How do I compare numbers in a bash if statement?
Use -eq, -ne, -lt, -le, -gt or -ge inside [ ] or [[ ]], for example [ "$n" -gt 10 ], or arithmetic with (( n > 10 )). Do not use < or > inside [[ ]] for numbers: they compare strings, so [[ 10 < 9 ]] is true.
Why does bash say unary operator expected?
A variable in a [ ] test was empty and unquoted, so it vanished and the operator was left without its left side, as in [ = yes ]. Put double quotes around the variable, [ "$x" = yes ], or switch to [[ $x == yes ]], which handles empty variables.