Conditional Statements with if, then, and fi
A conditional statement lets a script choose what to do based on a result. Without one, a script runs every line from top to bottom no matter what happened earlier. With one, a script can check whether a file exists before reading it, whether a command succeeded before moving on, or whether a number is large enough to justify a warning. In Bash, the basic conditional is the if statement, written with three keywords: if, then, and fi.
Understanding the Concept
Most programming languages evaluate a Boolean expression such as x > 5 and branch on true or false. Bash works differently. An if statement does not evaluate an expression. It runs a command and looks at that command's exit status.
Every command ends with a number between 0 and 255 called its exit status. By convention, 0 means success and anything else means failure or a special condition. The if statement turns that number into a decision:
- Exit status
0is treated as true, so thethenblock runs. - Any non-zero exit status is treated as false, so the
thenblock is skipped.
This is the reverse of what C and Java programmers expect, where 0 is false. In Bash, 0 means "everything went fine," and "everything went fine" is what the condition asks about. Lesson 116 covers exit statuses in detail; for now, remember that if asks one question: did the command succeed?
Syntax
if COMMAND
then
COMMANDS_TO_RUN_WHEN_COMMAND_SUCCEEDS
fi
The pieces are:
ifstarts the statement and is followed by the condition, which is any command or list of commands.thenstarts the block of commands that run when the condition succeeds.fiends the statement. It isifspelled backward, and it is required. Bash has no braces for this construct, sofiis the only thing that marks where the block ends.
Because then is a separate keyword, Bash needs to know where the condition command ends. A newline or a semicolon does that. These two forms are identical:
if [ -f notes.txt ]
then
echo "notes.txt exists"
fi
if [ -f notes.txt ]; then
echo "notes.txt exists"
fi
The second form, with ; then on the same line as if, is the one most scripts use. Indent the body so the structure is visible, although Bash itself ignores the indentation.
Basic Example
The simplest possible condition uses the built-in commands true and false, which do nothing except succeed and fail:
if true; then echo "true ran"; fi
if false; then echo "false ran"; fi
Output:
true ran
true exits with status 0, so the first echo runs. false exits with status 1, so the second echo is skipped. Nothing is printed for it and no error appears, because a skipped block is not an error.
Using Any Command as a Condition
Because the condition is just a command, you can put any command there. A very common choice is grep -q, which searches for text and prints nothing (-q means quiet) but still sets its exit status: 0 when a match is found, 1 when it is not.
printf 'alpha\nbeta\n' > names.txt
if grep -q beta names.txt; then
echo "beta found"
fi
if grep -q gamma names.txt; then
echo "gamma found"
fi
Output:
beta found
The first grep finds beta and exits with 0, so its block runs. The second finds no gamma, exits with 1, and its block is skipped.
This design is why Bash scripts read so naturally: if grep -q ..., if cp ..., if mkdir ..., if ping -c 1 .... Each reads as "if this command works, then do that." Later lessons show how to handle the case where it does not work.
Testing Conditions with [ ]
Most conditions are comparisons rather than plain commands: is this file present, is this number bigger than that one, are these two strings equal? Bash handles them with a command written as [ ... ] (the test command). It evaluates the expression between the brackets and exits with 0 or 1:
if [ -f names.txt ]; then
echo "file exists"
fi
Output:
file exists
The [ here is not special if syntax. It is an ordinary command, which is why it needs a space after [ and a space before ]. Lesson 68 explains test and [ ] fully, lesson 69 introduces the more capable [[ ]], and lessons 71 and 73 cover file tests and numeric comparisons. This lesson focuses on the if statement itself.
Understanding the Example
When Bash runs if [ -f names.txt ]; then, it goes through these steps:
- It parses the keyword
ifand recognizes that a condition follows. - It runs the command
[ -f names.txt ]. - That command checks whether
names.txtis a regular file and exits with 0 if so. - Bash reads the status. Status 0 means it enters the
thenbranch. - When it reaches
fi, the statement is finished and the script continues with the next line.
Nothing here is evaluated in an if-specific way. The same command typed on its own line would run identically; if only reads its status.
Conditions That Contain Several Commands
The condition can be a list of commands separated by semicolons or newlines. Bash runs all of them and uses the exit status of the last one:
if false; true; then
echo "last command true decides"
fi
if true; false; then
echo "not printed"
else
echo "last command false decides"
fi
Output:
last command true decides
last command false decides
This is legal but rarely useful, and it is easy to misread. When you want more than one test to matter, combine them with && and || inside the condition, as described next, rather than listing commands separated by semicolons.
Combining Conditions
The operators from lesson 65 work inside a condition. With &&, both commands must succeed:
if [ -f names.txt ] && grep -q alpha names.txt; then
echo "both true"
fi
Output:
both true
Here Bash first checks that names.txt exists. Only if that succeeds does it run grep. The if then looks at the status of the whole list. This also protects you: grep is never run on a file that does not exist. Lesson 74 covers logical operators in more depth.
A pipeline can also be a condition. Its status is that of the last command in the pipeline:
if printf 'a\nb\n' | grep -q b; then
echo "pipeline true"
fi
Output:
pipeline true
Negating a Condition
To run a block when a command fails, put ! in front of it. The ! reverses the exit status: success becomes failure and failure becomes success.
if ! grep -q gamma names.txt; then
echo "gamma missing"
fi
Output:
gamma missing
grep -q gamma fails (status 1), the ! flips that to success, and the block runs. Negation is the clearest way to write "if this is not the case." Leave a space after the !.
Using a Function as a Condition
A function that returns a status works as a condition just like a command. This lets you give a name to a check and reuse it:
is_even() { [ $(( $1 % 2 )) -eq 0 ]; }
if is_even 4; then echo "4 even"; fi
if is_even 5; then echo "5 even"; else echo "5 odd"; fi
Output:
4 even
5 odd
The function's status is the status of its last command, the [ ... ] test. Lessons 88 to 91 cover functions and return values. The else branch used on the second line is the subject of lesson 67.
Nesting if Statements
An if statement can appear inside the body of another one. Each if needs its own fi, and the innermost fi closes the innermost if:
n=15
if [ "$n" -gt 10 ]; then
echo "bigger than 10"
if [ "$n" -gt 12 ]; then
echo "also bigger than 12"
fi
fi
Output:
bigger than 10
also bigger than 12
Indentation is what makes nested statements readable. When the nesting goes more than two levels deep, the usual fix is to combine conditions with && or to move the inner part into a function.
Empty Bodies and the : Command
Bash does not allow a then block with nothing in it. This is a syntax error:
if [ -f x ]; then
fi
syn3.sh: line 2: syntax error near unexpected token `fi'
syn3.sh: line 2: `fi'
If you really need an empty branch, for example while sketching a script, use the : command. It is a built-in that does nothing and always succeeds:
if true; then :; fi
The Exit Status of an if Statement
An if statement has an exit status of its own, and it is easy to misunderstand:
- If a
thenblock ran, the status is the status of the last command in that block. - If the condition failed and there was no
else, the status is0.
if grep -q gamma names.txt; then echo x; fi
echo "status when no branch ran: $?"
if true; then (exit 3); fi
echo "status when the body ends with exit 3: $?"
Output:
status when no branch ran: 0
status when the body ends with exit 3: 3
The first line reports 0 even though grep failed, because a skipped if is not itself a failure. This matters when a script checks $? right after an if, or when it ends with an if statement, since that status becomes the script's own exit status.
Behavior Inside if: Errors and set -e
A failing condition is not treated as an error. The shell remembers that the command is being tested, so even in a script that uses set -e (which stops the script when a command fails, see lesson 119), a failing command in an if condition does not stop anything:
( set -e; if false; then echo no; fi; echo "survived" )
Output:
survived
Likewise, a command that does not exist simply fails:
if nosuchcmd_xyz 2>/dev/null; then
echo y
else
echo "status 127 treated as false"
fi
Output:
status 127 treated as false
Status 127 means "command not found." Any non-zero value counts as false, so the else branch runs. The 2>/dev/null hides the error message that Bash would otherwise print on standard error (see lesson 59).
The same technique keeps a noisy command quiet when only its status matters:
if ls /nonexistent_dir 2>/dev/null; then
echo y
else
echo "ls failed quietly"
fi
Output:
ls failed quietly
Syntax Rules to Remember
The punctuation of if is strict. These are the failures you are most likely to see.
then must start a new command, so it needs a newline or semicolon before it:
if true then echo hi; fi
syn.sh: line 1: syntax error near unexpected token `fi'
syn.sh: line 1: `if true then echo hi; fi'
Without the semicolon, Bash reads then as an argument to true, so the if never finds its own then.
A missing fi leaves the statement open until the file ends:
if true; then echo hi
syn2.sh: line 2: syntax error: unexpected end of file
A missing space before the closing bracket is a different failure, because [ is a command and ] must be a separate argument:
if [ -f x] ; then echo; fi
syn4.sh: line 1: [: missing `]'
Here the [ command fails with status 2, so the condition is false and the block is skipped. The script keeps running, which makes this kind of typo easy to overlook. Lesson 77 revisits conditional problems like this one.
Error messages in these examples show the script.sh: line N: prefix that Bash prints when it runs a script file. In an interactive terminal the prefix is bash: instead.
Practical Applications
A realistic use of if is to protect a command that would fail or do damage if a prerequisite were missing. This script creates a backup folder only when it does not already exist, and copies a file only when the source is present:
#!/usr/bin/env bash
source_file="notes.txt"
backup_dir="backups"
if [ ! -d "$backup_dir" ]; then
mkdir "$backup_dir"
echo "Created $backup_dir"
fi
if [ -f "$source_file" ]; then
cp "$source_file" "$backup_dir/"
echo "Copied $source_file"
fi
Running it twice in a folder that holds notes.txt prints this the first time:
Created backups
Copied notes.txt
and only Copied notes.txt the second time, because backups already exists. The variables are written inside double quotes so that names containing spaces stay in one piece (lesson 55 explains why).
Another common pattern is acting on the success of a command directly, without a separate test:
if mkdir reports; then
echo "reports folder created"
else
echo "could not create reports"
fi
This avoids the extra check "does the folder exist?" and reports the real outcome of the command that matters.