if & Test Expressions in Bash

From the Bash Scripting cheat sheet · Conditionals · verified Jul 2026

if & Test Expressions

if/elif/else with [[ ]].

bash
# Quick Reference
if [[ "$x" == "yes" ]]; then
    echo "ok"
elif [[ -z "$x" ]]; then
    echo "empty"
else
    echo "no"
fi
💡 Use [[ ]] (bash) over [ ] (POSIX test) - it handles empty vars, &&, and patterns safely.
⚡ == does glob-pattern matching in [[ ]]; =~ does regex matching.
📌 String tests: == != -z (empty) -n (non-empty). Numeric: -eq -ne -lt -gt -le -ge.
🟢 cmd && success || failure is a compact if/else, but beware if success itself can fail.
conditionalstest

More Bash tasks

Back to the full Bash Scripting cheat sheet