Using elif and else

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 67 of 205

A plain if statement answers a yes-or-no question: run this block, or skip it. Real scripts usually need more. They need a fallback when the test fails, or a choice among three or four possibilities. Bash provides two extra keywords for this: else, which supplies a default branch, and elif, which adds further tests. Together with if, they build a decision chain in which exactly one branch runs.

Understanding the Concept

Think of the whole if statement as a list of questions asked in order. Bash asks the first question. If the answer is yes, it runs that branch and stops asking. If the answer is no, it asks the next question, and so on. When no question is answered with yes, the else branch, if there is one, runs as the final default.

Two consequences follow from this:

  • At most one branch of the statement ever runs.
  • The order of the tests matters, because the first test that succeeds wins.

Syntax

if CONDITION_1; then
    COMMANDS_1
elif CONDITION_2; then
    COMMANDS_2
elif CONDITION_3; then
    COMMANDS_3
else
    DEFAULT_COMMANDS
fi

The parts are:

  • if starts the statement with the first condition, as in lesson 66.
  • elif (short for "else if") adds another condition. You can use as many elif parts as you need, and each one has its own then.
  • else introduces the default branch. It has no condition and no then.
  • fi ends the entire statement once, no matter how many elif parts it has.

Both elif and else are optional. The conditions are ordinary commands, exactly as in a simple if, so everything from lesson 66 about exit statuses still applies: a command that exits with 0 is true and any other status is false.

Basic Example: if and else

The simplest extension is a two-way choice:

n=3
if [ "$n" -gt 5 ]; then
    echo "big"
else
    echo "small"
fi

Output:

small

The test [ "$n" -gt 5 ] asks whether n is greater than 5. With n=3 it exits with status 1, so Bash skips the then branch and runs the else branch. Exactly one of the two echo commands always runs, which is the guarantee an else provides.

Choosing Among Many Options with elif

When there are more than two outcomes, chain the tests with elif. This script converts numeric scores into letter grades:

for score in 95 83 71 64 20; do
    if [ "$score" -ge 90 ]; then
        grade=A
    elif [ "$score" -ge 80 ]; then
        grade=B
    elif [ "$score" -ge 70 ]; then
        grade=C
    elif [ "$score" -ge 60 ]; then
        grade=D
    else
        grade=F
    fi
    echo "$score -> $grade"
done

Output:

95 -> A
83 -> B
71 -> C
64 -> D
20 -> F

Understanding the Example

Take the score 83:

  1. Bash tests 83 -ge 90. This is false, so it moves on.
  2. Bash tests 83 -ge 80. This is true, so it assigns grade=B.
  3. Bash skips every remaining elif and the else, and jumps to fi.
  4. The echo after fi prints 83 -> B.

Notice that the second test does not need to say "80 or more but below 90." By the time Bash reaches an elif, every earlier test has already failed, so the score must be below 90. Each condition only has to describe the lower limit of its range. This keeps the chain short and easy to read.

The score 20 fails every test, so the else branch assigns F. Without the else, grade would keep its value from the previous loop pass, which is a subtle way for a script to produce wrong output. Putting a default in the chain avoids that.

The -ge operator means "greater than or equal to." Lesson 73 covers the numeric comparison operators.

The First Matching Branch Wins

Because Bash stops at the first successful test, tests that overlap are never both reached. Here the second condition can never run:

x=100
if [ "$x" -gt 10 ]; then
    echo "over 10"
elif [ "$x" -gt 50 ]; then
    echo "over 50 (never reached)"
fi

Output:

over 10

100 is greater than both 10 and 50, but the first test already succeeded, so the elif is never evaluated. The fix is to put the most specific test first: check -gt 50 before -gt 10. When a chain of tests is ordered from narrowest to broadest, or from highest threshold to lowest as in the grade example, each branch can only be reached by the values it is meant for.

Using Commands as Conditions in a Chain

Every condition in the chain can be a different kind of command, not just a comparison. This example checks whether a word appears in a file, and gives different answers depending on why it did not:

printf 'alpha\nbeta\n' > names.txt
word=beta

if grep -q "^$word\$" names.txt; then
    echo "$word present"
elif [ -f names.txt ]; then
    echo "file exists but no $word"
else
    echo "no file"
fi

Output for word=beta:

beta present

Output after changing to word=zeta:

file exists but no zeta

Output after renaming the file so names.txt no longer exists (with the grep error hidden using 2>/dev/null):

no file

The three runs take three different paths through the same statement. The first grep pattern ^$word\$ matches a whole line equal to the word: ^ anchors the start, and the escaped \$ keeps the dollar sign for grep so it anchors the end, while the unescaped $word is replaced by the shell with the value. The elif only runs when the first test failed, which here means either the word was missing or the file could not be read, and the elif separates those cases.

else if Compared with elif

You can nest a whole if statement inside an else branch, written as else followed by a new if:

v=7
if [ "$v" -lt 5 ]; then
    echo low
else
    if [ "$v" -lt 10 ]; then
        echo mid
    fi
fi

Output:

mid

This works, but it needs two fi keywords and an extra level of indentation for every test. elif does the same job with one fi, and the chain stays flat:

if [ "$v" -lt 5 ]; then
    echo low
elif [ "$v" -lt 10 ]; then
    echo mid
fi

Remember the spelling: it is elif, never else if as one construct and never elseif.

The Exit Status of the Whole Statement

As in a simple if, the status of the whole statement is the status of the last command that ran in the branch that was chosen:

if false; then
    echo a
else
    (exit 4)
fi
echo "status: $?"

Output:

status: 4

The else branch ran (exit 4), which exits its subshell with status 4, and that became the status of the statement. If no branch ran at all (every test failed and there was no else), the status is 0, as lesson 66 explained.

Syntax Errors with elif and else

The rules for else and elif are strict, and the error messages Bash gives are about the token it did not expect, not the real cause.

else and elif must be followed by commands. An empty else is an error:

if true; then echo a; else; fi
s1.sh: line 1: syntax error near unexpected token `;'
s1.sh: line 1: `if true; then echo a; else; fi'

Use : as a do-nothing command if you really need an empty branch.

else must come last. An elif after an else is rejected:

if false; then echo a; else echo b; elif true; then echo c; fi
s2.sh: line 1: syntax error near unexpected token `elif'
s2.sh: line 1: `if false; then echo a; else echo b; elif true; then echo c; fi'

elseif is not a keyword. Bash treats it as the name of a command, so the then after it is unexpected:

if false; then echo a; elseif true; then echo c; fi
s3.sh: line 1: syntax error near unexpected token `then'
s3.sh: line 1: `if false; then echo a; elseif true; then echo c; fi'

Every elif needs its own then. Here the then line is missing:

if false; then echo a
elif true
  echo c
fi
s4.sh: line 4: syntax error near unexpected token `fi'
s4.sh: line 4: `fi'

Bash read true and echo c together as the condition of the elif, so the fi arrived before any then.

Writing else if on one line without closing the inner statement leaves the outer one open, which Bash reports at the end of the file:

if false; then echo a; else if true; then echo c; fi
s5.sh: line 2: syntax error: unexpected end of file

The single fi closes the inner if, and the outer if is still waiting for its own fi.

The messages above show the script.sh: line N: prefix that Bash prints for script files. In an interactive terminal the prefix is bash: instead.

Practical Applications

A script that accepts a path and reports what it is makes use of every part of the chain. It handles a missing argument first, then separate kinds of paths, and falls back to an error message:

#!/usr/bin/env bash

path="$1"

if [ -z "$path" ]; then
    echo "Usage: $0 PATH"
elif [ -d "$path" ]; then
    echo "$path is a directory"
elif [ -f "$path" ]; then
    echo "$path is a regular file"
else
    echo "$path does not exist"
fi

Saved as kind.sh and run with different arguments:

$ bash kind.sh
Usage: kind.sh PATH
$ bash kind.sh /etc
/etc is a directory
$ bash kind.sh /etc/hostname
/etc/hostname is a regular file
$ bash kind.sh /nothing/here
/nothing/here does not exist

The order is deliberate. The empty-argument test comes first because the later tests would behave oddly with an empty string. The -z test is true when a string has zero length, and -d and -f check for a directory and a regular file. Lesson 71 and 72 explain these file tests. When the number of choices grows large and each one compares the same value, the case statement in lesson 75 is often easier to read than a long elif chain.

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 Using elif and else and get answers drawn from it.

Signed-in readers only.