Script Valley
Bash Scripting for Developers
Control Flow and LogicLesson 2.1

Bash if statements and test conditions

if elif else syntax, test command, [ ] vs [[ ]], string comparison, numeric comparison operators, file test operators, compound conditions

if Statements in Bash

if-elif-else flow

Bash if evaluates the exit code of a command. Zero (success) = true. Non-zero = false. The [[ ]] test construct is the modern replacement for the old [ ] โ€” use it unless you specifically need POSIX portability.

#!/usr/bin/env bash
file="/etc/hosts"

if [[ -f "$file" ]]; then
  echo "File exists"
elif [[ -d "$file" ]]; then
  echo "It's a directory"
else
  echo "Not found"
fi

Comparison Operators

# String comparisons
[[ "$a" == "$b" ]]
[[ "$a" != "$b" ]]
[[ -z "$a" ]]   # true if empty string
[[ -n "$a" ]]   # true if non-empty

# Numeric comparisons
[[ $x -eq $y ]] # equal
[[ $x -ne $y ]] # not equal
[[ $x -lt $y ]] # less than
[[ $x -ge $y ]] # greater than or equal

# File tests
[[ -f "$path" ]]  # is regular file
[[ -d "$path" ]]  # is directory
[[ -r "$path" ]]  # is readable
[[ -x "$path" ]]  # is executable

Compound Conditions

# AND
if [[ -f "$file" && -r "$file" ]]; then
  cat "$file"
fi

# OR
if [[ $USER == "root" || $EUID -eq 0 ]]; then
  echo "Running as root"
fi

Never use == for numeric comparison โ€” use -eq. String == on numbers works but can break with leading zeros.

Up next

Bash for loops and while loops with examples

Sign in to track progress

Bash if statements and test conditions โ€” Control Flow and Logic โ€” Bash Scripting for Developers โ€” Script Valley โ€” Script Valley