Script Valley
Linux & Bash for Developers
Bash Scripting FundamentalsLesson 3.3

Bash if else and conditional statements

if elif else syntax, test command, [ ] vs [[ ]], string comparison, numeric comparison, file tests -f -d -e, && || operators

Conditionals Control Script Flow

Bash conditionals use the if keyword followed by a command whose exit code is tested. [ ] is the classic test command. [[ ]] is a Bash built-in that supports regex and handles quoting more safely โ€” prefer it in Bash scripts.

String and Numeric Comparisons

#!/bin/bash

ENV="production"

if [[ "$ENV" == "production" ]]; then
  echo "Running in production"
elif [[ "$ENV" == "staging" ]]; then
  echo "Running in staging"
else
  echo "Unknown environment: $ENV"
fi

# Numeric comparisons use -eq -ne -lt -gt -le -ge
COUNT=10
if [[ $COUNT -gt 5 ]]; then
  echo "Count exceeds threshold"
fi

File Test Operators

# -f: is a regular file
# -d: is a directory
# -e: exists (file or directory)
# -r -w -x: readable, writable, executable
# -z: string is empty
# -n: string is non-empty

if [[ -f "/etc/nginx/nginx.conf" ]]; then
  echo "Nginx config found"
fi

if [[ ! -d "$OUTPUT_DIR" ]]; then
  mkdir -p "$OUTPUT_DIR"
fi

Inline Conditionals

# Short-circuit: run second command only if first succeeds
mkdir -p logs && echo "logs dir ready"

# Run second command only if first fails
cp backup.tar /mnt/nas || echo "WARNING: backup copy failed"

Up next

Bash loops: for while and until explained

Sign in to track progress

Bash if else and conditional statements โ€” Bash Scripting Fundamentals โ€” Linux & Bash for Developers โ€” Script Valley โ€” Script Valley