Bash If/Else Conditions - Tests, Comparisons, and File Checks

Master bash conditional statements with if/elif/else, test operators for strings, numbers, and files, and the [[ ]] extended test syntax.

Control Flow

Detailed Explanation

Conditional Statements in Bash

Conditional statements control the flow of execution based on tests and comparisons. Bash provides the if/elif/else construct along with powerful test operators.

Basic If/Else

if [ condition ]; then
  echo "Condition is true"
elif [ other_condition ]; then
  echo "Other condition is true"
else
  echo "Neither condition is true"
fi

File Test Operators

These operators check file attributes:

-f FILE    # file exists and is a regular file
-d DIR     # directory exists
-e PATH    # path exists (any type)
-r FILE    # file is readable
-w FILE    # file is writable
-x FILE    # file is executable
-s FILE    # file exists and is not empty
-L FILE    # file is a symbolic link

Example:

if [ -f "config.yaml" ]; then
  echo "Config found, loading..."
  source config.yaml
elif [ -f "config.yaml.example" ]; then
  echo "Using example config"
  cp config.yaml.example config.yaml
else
  echo "Error: No config file found"
  exit 1
fi

String Comparisons

[ "$str" = "value" ]     # equal
[ "$str" != "value" ]    # not equal
[ -z "$str" ]            # string is empty
[ -n "$str" ]            # string is not empty

Numeric Comparisons

[ "$a" -eq "$b" ]   # equal
[ "$a" -ne "$b" ]   # not equal
[ "$a" -lt "$b" ]   # less than
[ "$a" -gt "$b" ]   # greater than
[ "$a" -le "$b" ]   # less than or equal
[ "$a" -ge "$b" ]   # greater than or equal

Extended Test [[ ]]

The [[ ]] syntax provides additional features:

# Pattern matching
if [[ "$filename" == *.txt ]]; then
  echo "Text file"
fi

# Regex matching
if [[ "$email" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
  echo "Valid email"
fi

# Logical operators
if [[ "$age" -ge 18 && "$country" == "US" ]]; then
  echo "Eligible"
fi

One-Line Conditionals

# Using && and ||
[ -f "file.txt" ] && echo "Exists" || echo "Missing"

# Ternary-like pattern
status=$([ "$code" -eq 0 ] && echo "success" || echo "failure")

Use Case

Conditional statements are used in every non-trivial bash script. Typical uses include checking if required files or directories exist before processing, validating user input and command-line arguments, branching logic based on environment variables (production vs. development), and implementing error handling with exit code checks.

Try It — Bash Cheat Sheet

Open full tool