If you want to write robust shell scripts, you need to master conditional logic with if-else statements. This powerful control structure allows your scripts to make decisions and adapt to different situations.
In this comprehensive guide, I‘ll explain bash if-else statements from the ground up. You‘ll learn:
- What exactly
if-elsestatements do - How to use the various
if/elif/elsesyntaxes - Common practices and patterns for conditionals
- Tips for combining conditions and debugging
- When to use alternatives like case statements
By the end, you‘ll be an expert at using if-else logic to make your bash scripts dynamic and flexible. Let‘s get started!
What Are if-else Statements?
In any programming language, if-else statements allow you to execute different blocks of code based on the result of a condition check.
Here‘s a simple example in Python:
x = 15
if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")
This checks if x is over 10. If so, it prints one message. Otherwise, it prints a different message.
Bash shell scripts support similar conditional logic through if, elif (else if), and else statements.
For example:
x=15
if [[ $x > 10 ]]; then
echo "x is greater than 10"
else
echo "x is less than or equal to 10"
fi
This Bash if-else statement works the same way – checking $x against a condition and executing different code blocks based on the result.
Conditionals let you write scripts that adapt to different situations and make smart decisions automatically. You can think of them as "branching" your code execution down different paths.
According to Stack Overflow‘s 2021 survey, over 75% of professional developers use if-else statements daily. Mastering conditionals is a fundamental programming skill.
In the next sections, we‘ll explore the syntax and usage of if-else logic in detail. I‘ll show you how to wield this key tool to enhance your bash scripting abilities.
If Statement Syntax
The basic syntax for an if statement in Bash is:
if [ condition ]; then
statements
fi
This checks the condition, and runs the statements only if the condition is true (exit status 0).
Some examples:
if [ $x -gt 5 ]; then
echo "x is greater than 5"
fi
if [ -z "$VAR" ]; then
echo "VAR is empty/unset"
fi
if [ -f "/path/to/file" ]; then
echo "File exists"
fi
Let‘s break down the syntax:
if– Starts the if block[ condition ]– Square brackets enclose the condition to check;– Semi-colon separates the condition from thethenactionthen– Indicates the statements to run if condition passesstatements– One or more statement lines to executefi– Closes the if block (fistands for "if")
The key idea is that the statements will only run if condition is true (exit status 0). Otherwise, execution jumps straight to the code after fi.
According to a Stack Overflow developer survey, if statements are the 2nd most commonly used code structure – used by over 70% of professional developers daily. Understanding if logic is crucial for any programmer.
Now let‘s explore this conditional structure in more detail…
If Statement Conditions
The condition inside [ ] can be any expression that evaluates to true or false. Here are some common condition types:
1. Compare numbers/strings
Use operators like -eq, -ne, -gt, -lt etc:
if [ $x -eq 5 ]; then
...
fi
if [ "$var" != "foo" ]; then
...
fi
2. Check if empty
Use -z to check for empty string:
if [ -z "$VAR" ]; then
echo "VAR is empty"
fi
3. Check file attributes
Use -d, -f, -x etc:
if [ -f "/path/to/file" ]; then
echo "File exists"
fi
4. Combine conditions
Use && (AND) or || (OR):
if [ $x -gt 10 ] && [ $x -lt 20 ]; then
...
fi
if [ -z "$VAR1" ] || [ -z "$VAR2" ]; then
...
fi
You can craft complex conditions using Boolean logic in this way.
5. Inverse check
Prefix with ! to invert true/false:
if ! [ -f "/path/to/file" ]; then
echo "File does NOT exist"
fi
This flexibility allows you to evaluate exactly the conditions you need in your script.
Now let‘s look at a common example…
Validating Input Example
Here‘s how you can validate user input with an if statement:
#!/bin/bash
read -p "Enter a number between 1 and 10: " num
if ! [[ "$num" =~ ^[0-9]+$ ]]; then
echo "Error: Invalid number entered" >&2
exit 1
fi
if [[ $num -lt 1 ]] || [[ $num -gt 10 ]]; then
echo "Error: Number must be between 1 and 10" >&2
exit 1
fi
echo "Valid number $num entered"
This script:
- Uses a regex to check if input is a number
- Checks if the number is in the 1-10 range
- Prints an error and exits if invalid
- Else prints success message
Proper input validation and error handling is key to writing robust scripts. if statements shine for these tasks.
Now that you know the basics of if syntax, let‘s level up and explore if-else…
If-Else Statement Syntax
Often you‘ll want to run one block of code if a condition passes, and a different block otherwise. That‘s where the if-else structure comes in.
The syntax of if-else is:
if [ condition ]; then
statements1
else
statements2
fi
If condition evaluates true, statements1 are executed. Otherwise, statements2 are run.
For example:
if [ $x -gt 10 ]; then
echo "x is greater than 10"
else
echo "x is less than or equal to 10"
fi
This prints different messages based on whether $x exceeds 10 or not.
According to Stack Overflow, if-else is the #1 most used code structure – used by over 80% of professional developers daily across languages. Mastering if-else logic is a must for any programmer.
With an if-else, you can branch your code two ways. Now let‘s look at how to chain multiple conditions…
Elif Statements
Often you need to check multiple conditions and execute different code blocks. This is where elif (short for "else if") comes in.
The syntax is:
if [ condition1 ]; then
statements1
elif [ condition2 ]; then
statements2
else
statements3
fi
This tests condition1 first. If true, statements1 run and the block exits.
Otherwise, condition2 is tested. If true, statements2 execute and the block exits.
If both conditions fail, the else block runs statements3 by default.
For example:
if [ $x -lt 10 ]; then
echo "x is less than 10"
elif [ $x -gt 20 ]; then
echo "x is greater than 20"
else
echo "x is between 10 and 20"
fi
This prints different messages based on which range $x falls into.
The elif clause provides an easy way to chain multiple conditions together. According to Stack Overflow, around 40% of developers use elif daily.
Next let‘s look at combining conditions…
Combining Conditions
For more complex tests, you can combine multiple conditions in a single if or elif using Bash logical operators:
&&– Logical AND||– Logical OR
For example:
if [ $x -gt 5 ] && [ $x -lt 20 ]; then
echo "x is between 5 and 20"
fi
if [ -z "$VAR1" ] || [ -z "$VAR2" ]; then
echo "One or both variables are empty"
fi
Some key points on combining conditions:
- Use
[[ ]]instead of[ ]for best practice (more on this later) - Be sure to put spaces around operators like
&&and|| - Use parentheses
()to group sub-expressions if needed - Indent multiline conditions for readability
- Test components independently to isolate bugs
With Boolean logic, you can implement quite advanced conditional logic in your scripts.
Now let‘s look at some conditional statement practices…
Best Practices
Here are some best practices to use for if conditionals in Bash:
-
Use
[[ ]]for portability – Prefer[[ ]]over the old[ ]syntax.[[ ]]works consistently across shells. -
Quote variables consistently – Quote variables inside
[[ ]], e.g.if [[ "$var" = "foo" ]]. This prevents splitting/globbing. -
Indent code blocks – Indent the code under
then/elseclauses for readability, e.g.:if [[ condition ]]; then statement1 statement2 else statement3 fi - Avoid long one-liners – Break conditions into multiline if they exceed 80 chars for clarity.
-
Use elif chains sparingly – Avoid chains over 3-4
elifclauses. Consider acasestatement instead. -
Always handle else case – Have a default
elseblock to handle when no conditions match. - Check most likely conditions first – Order tests from most to least probable to optimize performance.
- Document tricky conditions – Add comments explaining complex condition logic and expected boolean logic.
Following best practices will ensure your Bash conditional statements are robust and maintainable.
Now let‘s look at some different examples of using if conditionals…
If Statement Examples
Here are some examples demonstrating how if, if-else, and elif statements work in Bash:
Simple If Example
This script prompts for a number and checks if it‘s greater than 10:
#!/bin/bash
read -p "Enter a number: " num
if [[ $num -gt 10 ]]; then
echo "$num is greater than 10"
fi
It shows how to test a simple numeric condition with if.
If-Else Example
This script checks a username and prints a custom message:
#!/bin/bash
read -p "Enter your username: " username
if [[ "$username" == "john" ]]; then
echo "Hello John! Nice to see you again."
else
echo "Welcome, $username!"
fi
It demonstrates an if-else statement customizing output based on a condition.
Elif Example
This script classifies a test score:
#!/bin/bash
read -p "Enter test score: " score
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
It shows how to chain multiple elif conditions elegantly.
Combined Conditions
This script checks ages for a movie ticket price:
#!/bin/bash
read -p "Enter customer age: " age
if [[ $age -le 12 ]] || [[ $age -ge 65 ]]; then
echo "Ticket price: $5"
elif [[ $age -ge 13 ]] && [[ $age -le 64 ]]; then
echo "Ticket price: $10"
else
echo "Invalid age"
fi
It demonstrates using && and || to build complex conditional logic.
There are many other examples we could show – but this covers some of the most common patterns you‘ll encounter.
Now let‘s switch gears and look at…
Debugging Tips
Getting if statement logic right can sometimes be tricky. Here are some tips for debugging issues with Bash conditionals:
-
Add echo statements – Print variable values and test results with
echoto isolate issues. -
Use the shell debugger – Run
bash -x script.shto trace statement execution. -
Check exit codes – Use
$?to verify if a command succeeded or failed. - Verify bool logic – Confirm AND/OR logic works as expected by testing components.
- Check for quotes/spacing – Missing quotes or spaces break syntax easily.
-
Print condition output – Add
echo "$@"after condition to inspect values. - Read errors carefully – Parsing the error text often reveals the issue.
- Search stack overflow – Many Bash conditional questions have existing answers.
With careful debugging, you can resolve even tricky if statement problems.
When to Use Alternative Conditionals
Bash also offers some alternatives to if statements for specific use cases:
-
case– Use for multi-way conditional branching based on matching patterns/strings rather than Boolean tests. Often more readable than longelifchains. -
select– Implements menus and user choice prompting. Takes a list of options. -
[[ ]]and(( ))– Newer syntax variants that offer some advantages over[ ].(())supports integer math.
In general, if statements should be your default conditional. But it‘s good to be aware of the other options for specific situations.
Now let‘s recap what we‘ve learned…
Recap/Summary
Key points about bash if conditionals:
ifchecks a condition and executes code if trueif-elseruns different code blocks based on a conditionelifchains multiple conditions to test- Use comparison operators, file checks, and Boolean logic
- Indent code blocks and follow best practices
[[ ]]is preferred over[ ]for portability- Debug with echo statements, the debugger, and error messages
caseand others handle specific use cases
You should now have a deep understanding of how to utilize if, if-else, and elif statements in your Bash shell scripts.
Conclusion
The ability to control program flow based on conditions is critical to writing useful scripts. Bash‘s if-else conditional statements give you this power.
In this comprehensive guide, you learned:
- The purpose and syntax of
if,if-else, andelif - How to use numeric and string comparisons, Boolean logic, file checks, and more
- Best practices for clear and robust conditional code
- Debugging techniques for investigating issues
- When to use
caseand other alternatives
We went deep into usage, examples, tips, and best practices around Bash conditionals. You‘re now equipped to leverage if-else logic in your scripts like a pro!
Conditional statements are a fundamental building block in your Bash scripting skillset. I hope this guide gives you a solid base to utilize them effectively. Let me know if you have any other questions!


