Bash if statement — syntax and examples
Master Bash if statements with [[ ]], [ ], and arithmetic (( )). Learn when to quote, when to use -eq vs ==, and how to chain conditions.
Tldr
Use `if [[ "$x" == "value" ]]; then ... fi` for string tests in Bash. Use `(( a > b ))` for arithmetic. Quote variables in [ ] and [[ ]] to avoid word-splitting. Chain with `&&` and `||` inside [[ ]] or use `elif` for multiple branches.
Intro
Bash if statements look simple but hide several quoting and operator traps. This guide shows the modern Bash syntax, the portable POSIX syntax, and the arithmetic form so you can pick the right test for each situation.
Steps
Name
String comparison with [[ ]]
Text
Double brackets are a Bash keyword, so they handle empty variables safely and support pattern matching. Quote both operands for literal comparison.
Name
Inequality and multiple branches
Text
Use `!=` for inequality and `elif` for additional branches. `else` catches everything else.
Name
File tests
Text
Use `-e`, `-f`, `-d`, `-r`, `-w`, `-x`, and `-s` to test filesystem properties. Always quote the path.
Name
Arithmetic tests with (( ))
Text
For numeric comparisons, use the arithmetic evaluator. It coerces empty variables to 0 and supports familiar operators.
Name
Portable single-bracket tests
Text
Use `[ ]` when the script must run under POSIX sh. Quote every expansion and use `=` instead of `==`.
Name
Negate and combine conditions
Text
Use `!` to negate, `&&` for AND, `||` for OR. Inside [[ ]] these are safe with unquoted operators; inside [ ] you must use separate tests.
Faq
Q
What is the difference between [ and [[?
A
[ is a POSIX test command; [[ is a Bash keyword. [[ handles empty variables, pattern matching, and logical operators more safely. Use [[ for Bash-only scripts and [ for POSIX sh.
Q
Why do I get "too many arguments"?
A
You forgot to quote a variable that contains spaces inside [ ]. Use [ "$x" = "value" ], not [ $x = "value" ].
Q
Should I use -eq or == for numbers?
A
Use == (or =) for string comparison and -eq/-gt/-lt for integer comparison inside [ ]. Better still, use (( )) for arithmetic, where you can use ==, >, < directly.