This tutorial explains the Bash if else statement: what it does, its syntax, and how to use it in real shell scripts. You’ll learn the basic if, if else, elif, and nested variants, plus common test conditions and practical examples you can run right away.
What Is the Bash if else Statement?
The if else statement is a conditional construct in the Bash shell that lets your script make decisions. It evaluates a command or test expression, and if that expression returns a zero exit status (success), it runs one block of code; otherwise it runs another. This is the core of any non-trivial script, enabling logic like “if the file exists, back it up; else, create it.”
Bash’s if is not a function or a builtin comparison operator like in C; it’s a shell keyword that runs a command and checks its exit code. That’s why you’ll see [[ ... ]], [ ... ], or even plain commands like grep inside the condition.
Basic Syntax and Structure
The general form of an if else statement in Bash is:
if condition
then
# commands when condition is true
else
# commands when condition is false
fi
Key points:
- The
ifline ends with the condition, and the next line must bethen(or; thenon the same line). - Every
ifmust be closed withfi(reverse ofif). - The
elseblock is optional; if omitted and the condition is false, nothing happens. - For multiple branches, use
elif(else if) betweenifandelse.
Example with elif:
if [[ $score -ge 90 ]]; then
echo "Grade: A"
elif [[ $score -ge 80 ]]; then
echo "Grade: B"
elif [[ $score -ge 70 ]]; then
echo "Grade: C"
else
echo "Grade: F"
fi
Test Conditions: [ ] vs [[ ]] vs (( ))
Bash offers several ways to write the condition. The most common are:
[ condition ](single bracket) – POSIX test command. Works in all shells, but requires spaces around brackets and uses-eq,-lt, etc. for numeric comparisons.[[ condition ]](double bracket) – Bash keyword. More powerful: supports&&,||, regex matching with=~, and no word-splitting issues.(( expression ))– Arithmetic evaluation. Best for integer math; you can use>,<,==directly.
For numeric comparisons in [[ ]] or [ ], use these operators:
-eq– equal-ne– not equal-gt– greater than-lt– less than-ge– greater than or equal-le– less than or equal
For string comparisons, use = (or == in [[ ]]) for equality and != for inequality. For file tests, common flags are -f (regular file), -d (directory), -e (exists), -r (readable), -w (writable), -x (executable).
Practical Examples You Can Run
Here are several ready-to-use examples that illustrate common scenarios.
1. Check if a file exists
#!/bin/bash
if [[ -f "/etc/passwd" ]]; then
echo "The file exists."
else
echo "File not found."
fi
2. Compare two numbers
#!/bin/bash
a=10
b=20
if (( a > b )); then
echo "a is greater"
elif (( a < b )); then
echo "b is greater"
else
echo "They are equal"
fi
3. Check if a variable is empty
#!/bin/bash
name=""
if [[ -z "$name" ]]; then
echo "Name is empty"
else
echo "Name is $name"
fi
4. Multiple conditions with && and ||
#!/bin/bash
age=25
if [[ $age -gt 18 && $age -lt 65 ]]; then
echo "Working age"
else
echo "Not working age"
fi
5. Using a command as the condition
#!/bin/bash
if grep -q "error" /var/log/syslog; then
echo "Errors found"
else
echo "No errors"
fi
Note the -q flag in grep suppresses output; the exit status is what matters.
Common Mistakes and Pitfalls
Beginners often run into these issues:
- Missing spaces around brackets.
if[$a -eq 1]is wrong; it must beif [ $a -eq 1 ]. The brackets are separate tokens. - Using
>inside single brackets. In[ ],>is a redirection operator, not a comparison. Use-gtor switch to(( )). - Forgetting
fi. Everyifneeds a closingfi; missing it causes a syntax error. - Using
=for numeric comparison. In[ ],=compares strings. For numbers, use-eq. - Quoting variables. Always quote
"$var"in[ ]to avoid word-splitting and globbing issues, especially if the variable might be empty. - Using
else ifinstead ofelif.else ifis not valid; you needelif.
Nested if Statements and Early Exit
You can nest if statements inside each other, but deep nesting hurts readability. Often you can flatten logic with elif or by combining conditions with && and ||.
Example of nesting:
#!/bin/bash
if [[ -d "$dir" ]]; then
if [[ -w "$dir" ]]; then
echo "Directory exists and is writable"
else
echo "Directory exists but not writable"
fi
else
echo "Directory does not exist"
fi
For early exit, you can use return (in a function) or exit (in a script) inside an if block to stop execution, which is often cleaner than a long if else chain.
if else in One Line (for quick commands)
You can write a simple if else on a single line using semicolons:
if [[ -f "$file" ]]; then echo "exists"; else echo "missing"; fi
This is handy for one-off commands in the terminal, but for scripts, multi-line is more readable. Also note that the then must be preceded by a semicolon or be on a new line.
Frequently Asked Questions
What is the difference between [ ] and [[ ]] in Bash if?
[ ] is the POSIX test command and works in any shell. [[ ]] is a Bash keyword that adds features like && and || inside the brackets, regex matching with =~, and does not require quoting variables as often because it does not perform word-splitting. For new Bash scripts, [[ ]] is generally recommended.
Can I use if else with strings?
Yes. Use [[ "$str1" == "$str2" ]] for equality, != for inequality, and -z or -n to check if a string is empty or non-empty. Remember to quote the variables to avoid issues with spaces.
How do I check if a command succeeded in an if statement?
Simply put the command directly after if. For example: if grep -q pattern file; then .... The condition is true if the command exits with status 0. You can also negate with ! before the command.
What is the correct syntax for multiple conditions?
Inside [[ ]], use && for AND and || for OR. Inside [ ], use -a and -o (but they are deprecated and can be unreliable). For arithmetic, use (( ... )) with && and || as well.
Why do I get "syntax error near unexpected token `fi'"?
This usually means a missing then or a missing space before the closing bracket. Check that every if has a then (either on the next line or after a semicolon) and that the condition is properly spaced. Also ensure the fi is on its own line or preceded by a semicolon.
Can I use if else to compare floating-point numbers?
Bash's built-in arithmetic only handles integers. For floating-point comparisons, use bc or awk. For example: if (( $(echo "$a > $b" | bc -l) )); then ... or use awk in a command substitution.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Secure Boot Battlefield 6 ASUS: Fix & Enable Guide
- Best Tech Websites to Follow for Pros & Beginners
- Second Wind Quest Walkthrough: Where Winds Meet6.00 min/km
- Enshrouded Weapon Upgrade Guide: How to Improve Gear5.00 min/km
- Connect Phone to Controller for Cloud Gaming
- Python Search Highlighting: Snippets & Matches