Skip to content
AgileLogics
6 min read

Conditionals: if and Tests

Prerequisites: Exit codes, &&, and ||

if runs code depending on whether a command succeeds.

Syntax

if condition; then
  # commands
elif other_condition; then
  # commands
else
  # commands
fi

The block ends with fi ("if" backwards). The condition is any command: exit status 0 counts as true.

Testing with [[ ]]

Usually the condition is a test in double square brackets:

temperature=18

if [[ $temperature -gt 25 ]]; then
  echo "It's hot"
elif [[ $temperature -gt 15 ]]; then
  echo "It's pleasant"
else
  echo "It's cold"
fi

Expected output

It's pleasant

Comparing numbers and text

Numbers Text Meaning
-eq == equal
-ne != not equal
-lt -gt < > less / greater than
-le -ge less / greater or equal

For numbers, (( )) often reads more naturally:

count=7
if (( count > 5 )); then echo "more than five"; fi

name="ada"
if [[ $name == "ada" ]]; then echo "hello, ada"; fi
if [[ $name == a* ]]; then echo "starts with a"; fi
more than five
hello, ada
starts with a

[[ $name == a* ]] compares against a pattern (like a wildcard).

Combining conditions

age=20
member="yes"
if [[ $age -ge 18 && $member == "yes" ]]; then
  echo "Welcome to the members' lounge"
fi
if [[ ! -e "missing.txt" ]]; then
  echo "missing.txt doesn't exist"
fi
Welcome to the members' lounge
missing.txt doesn't exist

&& (and), || (or), and ! (not) work inside [[ ]].

[[ ]] vs [ ]

[ ] (single brackets, also called test) is the older, portable POSIX form. [[ ]] is Bash's improved version: safer with empty variables, supports && and pattern matching, and doesn't need as much quoting. Prefer [[ ]] in Bash scripts; use [ ] in scripts meant for plain sh.

Common mistakes

  • Missing spaces: [[$a == $b]] is an error. There must be spaces inside the brackets and around the operator.
  • Using == or > to compare numbers: [[ 10 > 9 ]] compares alphabetically and is false ("1" sorts before "9"). Use -gt or (( 10 > 9 )).

Practice

Given score=72, print pass if it's 50 or more, otherwise fail.

Show solution
score=72
if (( score >= 50 )); then
  echo "pass"
else
  echo "fail"
fi
pass