Conditional Statements with if, then, and fi

Su Suriya Ravichandran Updated 06 Dec 2026
11 min read ·Lesson 66 of 205

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 0 is treated as true, so the then block runs.
  • Any non-zero exit status is treated as false, so the then block 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:

  • if starts the statement and is followed by the condition, which is any command or list of commands.
  • then starts the block of commands that run when the condition succeeds.
  • fi ends the statement. It is if spelled backward, and it is required. Bash has no braces for this construct, so fi is 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:

  1. It parses the keyword if and recognizes that a condition follows.
  2. It runs the command [ -f names.txt ].
  3. That command checks whether names.txt is a regular file and exits with 0 if so.
  4. Bash reads the status. Status 0 means it enters the then branch.
  5. 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 then block ran, the status is the status of the last command in that block.
  • If the condition failed and there was no else, the status is 0.
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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Conditional Statements with if, then, and fi and get answers drawn from it.

Signed-in readers only.