0
0
Bash-scriptingHow-ToBeginner · 3 min read

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 check
  • condition: a command or test that returns true or false
  • then: begins the commands to run if condition is true
  • else: begins the commands to run if condition is false
  • fi: 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

KeywordPurpose
ifStart condition check
[ condition ]Test condition with spaces around brackets
thenCommands if condition is true
elseCommands if condition is false
elifElse if for multiple conditions
fiEnd 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.