Back to roadmaps shell-script Course

Conditional Logic: if Statements and case Switches

Conditional logic allows scripts to make decisions based on the state of the system or input values.


1. The if Statement Syntax

The basic structure of a Bash conditional block:

#!/bin/bash
DISK_USAGE=$(df / | awk 'NR==2 {print $5}' | tr -d '%')

if [ "$DISK_USAGE" -gt 90 ]; then
  echo "CRITICAL: Disk usage is above 90%!"
elif [ "$DISK_USAGE" -gt 75 ]; then
  echo "WARNING: Disk usage is above 75%."
else
  echo "OK: Disk usage is at ${DISK_USAGE}%."
fi

2. Common Test Operators

Operator Test Type Example
-eq Numbers are equal [ "$COUNT" -eq 10 ]
-gt Number is greater than [ "$SIZE" -gt 100 ]
-lt Number is less than [ "$COUNT" -lt 0 ]
= Strings are equal [ "$ENV" = "production" ]
!= Strings are not equal [ "$STATUS" != "ok" ]
-f File exists and is a regular file [ -f "/etc/nginx.conf" ]
-d Directory exists [ -d "/var/www/html" ]

3. The case Switch Statement

For matching one variable against multiple patterns:

#!/bin/bash
ENVIRONMENT=$1

case "$ENVIRONMENT" in
  production)
    echo "Deploying to production server..."
    ;;
  staging)
    echo "Deploying to staging server..."
    ;;
  *)
    echo "Unknown environment: $ENVIRONMENT"
    exit 1
    ;;
esac
Published on Last updated: