How to Use If Else in Bash: Simple Syntax and Examples
In bash, use
if followed by a condition and then to run commands if true. Use else to run commands if the condition is false, ending with fi to close the block.Syntax
The basic if else structure in bash looks like this:
if: starts the condition checkcondition: a command or test that returns true or falsethen: begins the commands to run if condition is trueelse: begins the commands to run if condition is falsefi: ends the if block
bash
if [ condition ]; then # commands if true else # commands if false fi
Example
This example checks if a number is greater than 10 and prints a message accordingly.
bash
#!/bin/bash number=15 if [ "$number" -gt 10 ]; then echo "Number is greater than 10" else echo "Number is 10 or less" fi
Output
Number is greater than 10
Common Pitfalls
Common mistakes include missing spaces around brackets, forgetting fi, or using incorrect test operators.
Wrong example (missing spaces):
if ["$number"-gt10]; then echo "Yes"; fi
Correct example:
bash
if [ "$number" -gt 10 ]; then echo "Yes" fi
Quick Reference
| Keyword | Purpose |
|---|---|
| if | Start condition check |
| [ condition ] | Test condition with spaces around brackets |
| then | Commands if condition is true |
| else | Commands if condition is false |
| elif | Else if for multiple conditions |
| fi | End if block |
Key Takeaways
Always put spaces around brackets in conditions: [ condition ].
Close every if block with fi to avoid syntax errors.
Use -gt, -lt, -eq for numeric comparisons inside [ ].
Use else to run commands when the if condition is false.
Test your script with simple examples to catch syntax mistakes early.