October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk7 min

How to Use If Else in Linux Shell Scripts

A practical guide to Bash and POSIX shell conditionals: syntax, exit-status logic, safe tests, file checks, portability, debugging, and case statements.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In a Linux shell script, an if statement runs one command list when a test command exits with status zero and can choose alternate lists with elif and else. Bash uses this form:

if test-commands; then
  consequent-commands
elif more-test-commands; then
  more-consequents
else
  alternate-consequents
fi

The middle and final branches are optional. The closing keyword is fi, and Bash evaluates conditions by exit status rather than by text printed to the terminal.

As an Amazon Associate I earn from qualifying purchases.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The basic Bash if/elif/else syntax

The reserved words if, then, elif, else and fi delimit the conditional construct. A test can be any command or command list. Put then after the test on the same line with a semicolon, or place it on the following line.

if command; then
  commands-when-successful
fi

if command
then
  commands-when-successful
fi

Use elif for additional tests in sequence. Bash does not use else if as a combined keyword; writing else followed by a nested if is valid, but it requires another matching fi and is usually harder to read.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
if first_test; then
  first_action
elif second_test; then
  second_action
else
  fallback_action
fi

How Bash decides which branch runs

Bash executes the test command list first. Exit status zero is treated as true, so the corresponding command list runs. A nonzero status is treated as false, causing Bash to try the next elif test. If all tests fail and an else branch exists, Bash runs that branch.

This means if checks a command’s status, not whether the command printed output. For example, grep -q can test whether text exists without displaying a match:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
if grep -q 'ERROR' application.log; then
  printf '%sn' 'Errors were found'
else
  printf '%sn' 'No errors were found'
fi

The status returned by the complete conditional is the status of the last command executed in the selected branch. If no condition is true and there is no else, the conditional returns zero because no condition tested true. Do not confuse that result with the status of a test that failed.

Choose the conditional form for your shell

The interpreter named by the shebang determines which syntax is available. Bash-specific constructs are convenient, but a script invoked with /bin/sh must use POSIX-compatible syntax.

Form Typical interpreter Strengths Important requirement
[[ ... ]] Bash Compound conditional syntax for string, numeric and file-attribute tests; ordinary string operands are handled more safely than with the old bracket command. Do not use it in a script whose interpreter is a shell that does not implement Bash conditionals.
(( ... )) Bash Readable arithmetic expressions such as score >= 90. It is Bash-specific.
[ ... ] or test POSIX sh and Bash Portable string, numeric and file tests. Every operator and operand must be a separate argument, and the closing ] is required.

Use a Bash shebang when you intend to use [[ ]] or (( )):

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
#!/usr/bin/env bash

For a portable script, use:

#!/bin/sh

Testing strings safely

[[ -z value ]] tests whether a string is empty. The following script accepts a name as its first argument and reports a usage error when it is missing:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#!/usr/bin/env bash

name=${1-}
if [[ -z "$name" ]]; then
  printf '%sn' 'Usage: script.sh NAME' >&2
  exit 2
else
  printf 'Hello, %sn' "$name"
fi

${1-} supplies an empty value when the first argument is unset. Quoting the expansion makes the intended single string explicit. In Bash’s [[ ]], ordinary string operands do not undergo the word-splitting and pathname expansion that commonly cause trouble with the single-bracket command, but quoting remains clear and consistent.

For POSIX sh, use separate arguments and quote expansions:

#!/bin/sh

name=${1-}
if [ -n "$name" ]; then
  printf '%sn' 'name is set'
else
  printf '%sn' 'name is empty'
fi

Here -n means the string has nonzero length. The spaces are syntax, not decoration: [ is a command, and the closing ] is its final argument.

Equality and the spacing rule

With the portable form, write:

if [ "$answer" = 'yes' ]; then
  printf '%sn' 'Continuing'
fi

Do not write [ "$answer"=yes ]. Without spaces, the shell passes a different set of arguments to the bracket command and the test can fail or produce a diagnostic. Quote variables because an empty value or whitespace can otherwise remove or split arguments.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Comparing numbers

Bash arithmetic conditions use (( ... )) and familiar mathematical operators:

#!/usr/bin/env bash

score=${1:-0}
if (( score >= 90 )); then
  printf '%sn' 'excellent'
elif (( score >= 60 )); then
  printf '%sn' 'pass'
else
  printf '%sn' 'needs improvement'
fi

The first true branch wins, so the highest threshold must come first. The default expression ${1:-0} uses zero when the argument is unset or empty.

In POSIX sh, use the test operators -ge, -gt, -eq, -ne, -lt and -le:

#!/bin/sh

score=${1:-0}
if [ "$score" -ge 90 ]; then
  printf '%sn' 'excellent'
elif [ "$score" -ge 60 ]; then
  printf '%sn' 'pass'
else
  printf '%sn' 'needs improvement'
fi

These operators compare numeric values; do not replace -ge with the string operator >= in a single-bracket POSIX test.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Checking files and directories

Bash’s compound conditional supports file-attribute tests such as -f for a regular file and -d for a directory:

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
#!/usr/bin/env bash

file=${1-}
if [[ -f "$file" ]]; then
  printf '%sn' 'regular file'
elif [[ -d "$file" ]]; then
  printf '%sn' 'directory'
else
  printf '%sn' 'missing or another file type'
fi

The same checks are portable with single brackets:

if [ -f "$file" ]; then
  printf '%sn' 'regular file'
elif [ -d "$file" ]; then
  printf '%sn' 'directory'
fi

Keep the path in a quoted variable. A path containing spaces should still be passed as one argument, and an unset path should not change the number of arguments received by the test command.

Combining conditions and controlling precedence

Within Bash’s [[ ]], combine expressions with && for “and” and || for “or”:

if [[ -n "$name" && "$name" != 'root' ]]; then
  printf '%sn' 'A non-root name was supplied'
fi

For portable scripts, separate command tests with shell lists:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
if [ -n "$name" ] && [ "$name" != 'root' ]; then
  printf '%sn' 'A non-root name was supplied'
fi

Use parentheses only when you understand the shell’s parsing rules, and group complex logic into clearly named tests or separate branches. A short, explicit conditional is easier to audit than a dense expression whose precedence is unclear.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Writing several alternatives: elif or case?

An elif chain is appropriate when each branch has a different test, such as numeric ranges or file attributes. When one value must be matched against several literal or pattern alternatives, case is often easier to scan:

case ${1-} in
  start)
    printf '%sn' 'Starting'
    ;;
  stop)
    printf '%sn' 'Stopping'
    ;;
  *)
    printf '%sn' 'Usage: script.sh {start|stop}' >&2
    exit 2
    ;;
esac

case is a separate conditional construct, not another spelling of if. Use it when the alternatives are primarily value patterns; use if when each decision involves a command status, range, or different kind of test.

A complete practical script

This Bash example validates an argument, distinguishes a regular file from a directory, and then reports the result. It demonstrates the order in which checks should be made and gives a nonzero status for invalid usage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#!/usr/bin/env bash

path=${1-}

if [[ -z "$path" ]]; then
  printf '%sn' 'Usage: inspect.sh PATH' >&2
  exit 2
elif [[ -f "$path" ]]; then
  printf 'Regular file: %sn' "$path"
elif [[ -d "$path" ]]; then
  printf 'Directory: %sn' "$path"
else
  printf 'Not a regular file or directory: %sn' "$path"
  exit 1
fi

The empty-argument check comes first so later file tests never operate on an unintended empty path. The script exits with status 2 for incorrect usage and status 1 for an existing path of another type; successful branches finish with the status returned by their final printf.

Why “syntax error near then” happens

The test line lacks a separator

This is invalid because Bash cannot tell where the test command ends:

if [[ -f "$file" ]] then

Use a semicolon before then or put then on its own line:

if [[ -f "$file" ]]; then
  printf '%sn' 'file'
fi

if [[ -f "$file" ]]
then
  printf '%sn' 'file'
fi

The closing bracket is missing

Single-bracket tests need both the opening [ and closing ] as separate tokens:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
if [ -f "$file" ]; then
  printf '%sn' 'file'
fi

The branch keyword is wrong

Use elif for a middle branch. If you write else if, Bash parses it as a new nested conditional, which needs its own then and fi.

The script is running under the wrong shell

A file containing [[ ]] or (( )) can fail when invoked through a POSIX shell. Make the shebang match the syntax and invoke the script directly, or rewrite the tests using [ ... ] for portability.

A reliable debugging workflow

  1. Check parsing without executing commands. Run bash -n script.sh. This catches unmatched fi, malformed brackets, and misplaced reserved words without running the script body.
  2. Trace the executed branches. Run bash -x script.sh, or place set -x before the failing section. The trace shows expanded commands and makes it clear which test returned false.
  3. Lint the script. ShellCheck performs static analysis for sh and Bash scripts and flags common syntax, quoting, and portability problems.
  4. Confirm the interpreter. Inspect the first line and how the script is launched. A Bash script run explicitly with another shell does not get Bash’s conditional syntax.
  5. Reduce the test. Replace a complicated condition temporarily with a simple command such as true or false, then add tests back one at a time. This separates parsing errors from unexpected command statuses.

Practical checklist

  • Close every conditional with fi.
  • Use elif, not a pseudo-keyword such as else if.
  • Separate the test command and then with a semicolon or newline.
  • Keep spaces around every operator and operand in [ ... ], and include the closing ].
  • Quote variable expansions in portable tests, especially when a value may be empty or contain whitespace.
  • Use [[ ... ]] and (( ... )) only when Bash is the interpreter.
  • Remember that status zero means true in an if condition, while nonzero means false.
  • Choose case when one value is being matched against many literal or pattern alternatives.
  • Run bash -n, then bash -x, and lint with ShellCheck when a conditional behaves unexpectedly.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.