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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

In a Bash script, an if statement runs a command list and treats exit status 0 as true. Use elif for additional tests, else for the fallback, and close the construct with fi:

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

The same structure works with string, numeric, and file tests. The important portability choice is whether the script runs under Bash (where [[ ... ]] and (( ... )) are available) or under a POSIX shell such as /bin/sh (where use [ ... ] or test).

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.

What an if statement actually tests

Shell conditionals do not test whether a command printed a particular word. They execute the test command list and inspect its exit status. Status 0 means success and is treated as true; any nonzero status is false. Bash executes the first true branch, skips the remaining branches, and returns the status of the last command it ran. If no condition succeeds and there is no else, the compound command returns zero.

This design lets you test ordinary commands directly:

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.
if grep -q '^admin:' /etc/passwd; then
  printf '%sn' 'An admin account exists'
else
  printf '%sn' 'No admin account was found'
fi

Here, grep -q supplies the condition through its exit status. The output of the command is irrelevant to the decision.

Basic Bash syntax

The reserved words that delimit the construct are if, then, elif, else, and fi. The elif and else clauses are optional, and you can have multiple elif clauses.

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

Putting then on the same line

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

A semicolon separates the test command from then when both are on one line. Without that separator, Bash interprets the line incorrectly and reports a syntax error.

Putting then on the next line

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

A newline terminates the test command, so no semicolon is needed in this form. Choose one style and apply it consistently.

Using several branches

if command-a; then
  printf '%sn' 'A succeeded'
elif command-b; then
  printf '%sn' 'B succeeded'
else
  printf '%sn' 'Both failed'
fi

Bash evaluates the tests from top to bottom. Once a test returns zero, its commands run and later tests are not evaluated.

A complete argument-checking example

This script demonstrates a common pattern: capture an optional argument, test it safely, and return a useful error status 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 no first argument was provided. The -z test is true for an empty string. The diagnostic is redirected to standard error, while a valid name is printed on standard output. Quoting "$name" preserves spaces and prevents word splitting.

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Choosing a condition syntax

There are three commonly encountered forms. Their capabilities overlap, but their portability and parsing rules differ.

Form Best use Interpreter requirement Important rules
[[ ... ]] Readable Bash string, numeric, file, and pattern conditions Bash Use as a Bash compound conditional; quote ordinary variable expansions
[ ... ] Portable single-condition tests POSIX shells and Bash [ is a command-like token; every argument needs separation and the closing ] is required
test ... The same portable tests without bracket notation POSIX shells and Bash Operators and operands remain separate arguments
(( ... )) Arithmetic comparisons and calculations Bash Use Bash as the interpreter; the expression’s arithmetic result determines status

If the file begins with #!/bin/sh, write POSIX-compatible tests. A Bash shebang such as #!/usr/bin/env bash is required before using [[ ... ]] or (( ... )).

String comparisons

Using Bash [[ ... ]]

[[ ... ]] is Bash’s compound conditional command. It supports unary and binary conditional expressions and is generally easier to read for ordinary string operands.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
name=${1-}

if [[ -z "$name" ]]; then
  printf '%sn' 'Name is empty'
elif [[ "$name" == 'root' ]]; then
  printf '%sn' 'The root account name was supplied'
else
  printf 'Name: %sn' "$name"
fi

Useful unary string checks include -z for an empty string and -n for a non-empty string. Binary operators compare values, for example == and !=.

Using POSIX [ ... ]

#!/bin/sh

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

With bracket syntax, spacing is part of the grammar. Write:

if [ "$x" = yes ]; then
  printf '%sn' 'enabled'
fi

Do not write [ "$x"=yes ]. In the latter form, the shell passes a different set of arguments to the bracket command, so the intended comparison is not performed.

Why quoting matters

Always quote variable expansions in portable bracket tests. An empty expansion can remove an argument, and a value containing whitespace can become several arguments. Both situations change how the test command parses its operands.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.
if [ "$answer" = yes ]; then
  printf '%sn' 'Continuing'
fi

Inside [[ ... ]], ordinary quoted expansions are still the clearest and safest habit. Keep pattern syntax intentional rather than relying on accidental expansion behavior.

Numeric comparisons

Bash arithmetic with (( ... ))

For Bash scripts, arithmetic evaluation gives a concise way to branch on numbers:

score=${1:-0}

if (( score >= 90 )); then
  printf '%sn' 'excellent'
elif (( score >= 60 )); then
  printf '%sn' 'pass'
else
  printf '%sn' 'needs improvement'
fi

The arithmetic expression itself determines the status: a nonzero result is true and zero is false. The variable name can be used directly inside (( ... )); you do not need the $ prefix.

POSIX numeric operators

In [ ... ] or test, use numeric operators rather than string operators:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#!/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

Common numeric operators include -eq (equal), -ne (not equal), -lt (less than), -le (less than or equal), -gt (greater than), and -ge (greater than or equal). Keep spaces around every operand and operator.

Checking files and directories

File-attribute tests let a script choose an action based on what a path refers to:

#!/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

-f succeeds for a regular file and -d succeeds for a directory. The final branch also covers a path that does not exist and file types not matched by those two tests. Add other file-attribute expressions when your script needs them, while keeping each branch’s purpose explicit.

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Combining conditions

When one branch depends on more than one fact, combine expressions in the conditional form supported by your shell. In Bash, [[ ... ]] can express compound conditions directly:

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.
if [[ -f "$config" && -r "$config" ]]; then
  printf '%sn' 'Readable configuration file'
else
  printf '%sn' 'Configuration is missing or unreadable'
fi

For POSIX scripts, separate tests with shell operators and group them deliberately:

if [ -f "$config" ] && [ -r "$config" ]; then
  printf '%sn' 'Readable configuration file'
fi

Keeping each bracket expression complete makes argument boundaries visible and avoids malformed tests.

When case is clearer than elif

Use if when conditions are ranges, file attributes, command results, or unrelated predicates. Use case when one value must be matched against several literal or pattern alternatives. A long chain that repeatedly compares the same variable is often easier to scan as a case construct:

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

case is a separate conditional construct, not another spelling of elif. Choose it when the alternatives are values or patterns rather than progressively tested conditions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Understanding branch and script exit statuses

The status of the entire if construct is the status of the last command executed in the selected branch. That detail matters when a function or a larger script relies on the conditional’s result.

if [[ -f "$path" ]]; then
  printf '%sn' 'Found'
  return 0
else
  printf '%sn' 'Not found' >&2
  return 1
fi

At top level, use exit instead of return. If you want the conditional itself to communicate success or failure, make the final command in each branch an intentional status-producing command.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.

Why “syntax error near then” happens

The test command was not terminated

On a one-line condition, then must follow a semicolon:

if [[ "$mode" == 'safe' ]]; then
  printf '%sn' 'Safe mode'
fi

Alternatively, place then on the next line. A missing semicolon or newline leaves Bash unable to tell where the test command ends.

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

The closing keyword is wrong

An if block closes with fi. The middle branch keyword is elif, not else if:

if condition-a; then
  command-a
elif condition-b; then
  command-b
else
  command-c
fi

Nested if statements are valid, but each nested construct needs its own matching fi. Use nesting only when a second decision genuinely belongs inside the first branch.

Bracket spacing is missing

Because [ is command-like syntax, these tokens must be separate:

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

The opening bracket, variable, operator, comparison value, and closing bracket are individual arguments. Missing any required space changes the command that the shell executes.

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

The script is running under the wrong shell

A script containing [[ ... ]] or (( ... )) can fail when invoked by a POSIX shell. Make the shebang match the syntax, then invoke the script in a way that honors it:

#!/usr/bin/env bash

If the script must remain /bin/sh-portable, replace Bash-only constructs with [ ... ], test, and POSIX arithmetic techniques.

A practical debugging workflow

  1. Check parsing first. Run bash -n script.sh. Bash reads the file without executing its commands, so this isolates syntax errors.
  2. Trace execution. Run bash -x script.sh, or place set -x around the failing section. The trace shows expanded commands and the branch that actually ran.
  3. Verify the interpreter. Read the shebang and compare it with the constructs in the file. A Bash-only conditional cannot be validated by assuming every sh implementation behaves like Bash.
  4. Lint the script. Run ShellCheck against the file. Its static analysis flags common shell syntax errors, quoting mistakes, and portability pitfalls that are easy to overlook during manual review.
  5. Test boundary inputs. Try no argument, an empty value, whitespace in a value, a nonexistent path, a directory where a file is expected, and values exactly on numeric thresholds.

Patterns that prevent common mistakes

  • Put a Bash shebang at the top when using [[ ... ]] or (( ... )).
  • Quote variable expansions in [ ... ] tests and in ordinary string comparisons.
  • Use elif for another branch at the same decision level; reserve nested if blocks for dependent decisions.
  • Keep one complete condition per line when a test becomes difficult to read.
  • Use numeric operators for numbers; do not substitute string equality for a numeric range test.
  • Use case when many alternatives all match one value.
  • Make fallback behavior explicit with else when silently doing nothing would hide an error.
  • Return an intentional status from error branches, especially when another command will consume the script’s result.

Quick reference

Need Bash example Portable form
Non-empty string [[ -n "$value" ]] [ -n "$value" ]
Equal strings [[ "$a" == "$b" ]] [ "$a" = "$b" ]
Numeric threshold (( count >= 10 )) [ "$count" -ge 10 ]
Regular file [[ -f "$path" ]] [ -f "$path" ]
Directory [[ -d "$path" ]] [ -d "$path" ]

Remember the four structural rules that prevent most errors: status zero is true, elif adds a same-level branch, fi closes the block, and bracket tests require exact spacing. Once those rules are in place, select [[ ... ]] and (( ... )) for Bash-specific scripts, or [ ... ] and test when portability to /bin/sh matters.

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.

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