if / test [ ]
Try it yourself →Executes code based on a condition.
Syntax
if [ condition ]; then ... else ... fi
Description
Tests are performed inside square brackets. Numbers: -eq -ne -lt -gt -le -ge. Text: = !=. Spaces inside brackets are MANDATORY.
Example
x=7 if [ $((x % 2)) -eq 0 ]; then echo "even" else echo "odd" fi
Expected output
odd
When to use?
Flow branching.
Common mistakes
- ⚠️ Spaces around [ and ] are required: [ $x -eq 0 ] (correct), [$x-eq0] (incorrect).