Last updated

Bash Scripting

Bash Scripting Essentials

Write robust bash scripts for automation and system administration.

Contents

  1. Script Structure
  2. Conditionals
  3. Loops
  4. Functions
  5. Error Handling
  6. Script Arguments

Script Structure

#!/bin/bash
set -euo pipefail  # exit on error, undefined vars, pipe failures
IFS=$'\n\t'       # safer word splitting

# Variables
NAME="world"
echo "Hello, $NAME"

Conditionals

if [[ -f /etc/passwd ]]; then
  echo "File exists"
elif [[ -d /tmp ]]; then
  echo "Directory exists"
else
  echo "Neither"
fi

# String comparison
if [[ "$USER" == "root" ]]; then
  echo "Running as root"
fi

# Numeric comparison
COUNT=5
if (( COUNT > 3 )); then
  echo "Count is greater than 3"
fi

Loops

# For loop over list
for server in web01 web02 db01; do
  echo "Checking $server..."
  ping -c 1 "$server" &>/dev/null && echo "  UP" || echo "  DOWN"
done

# While loop
COUNT=0
while (( COUNT < 5 )); do
  echo "Count: $COUNT"
  (( COUNT++ ))
done

# Loop over files
for f in /etc/*.conf; do
  echo "Config: $f"
done

Functions

log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a /var/log/myscript.log
}

check_service() {
  local svc="$1"
  systemctl is-active --quiet "$svc" && log "$svc is running" || log "WARNING: $svc is down"
}

check_service nginx
check_service mysql

Error Handling

cleanup() {
  echo "Cleaning up..."
  rm -f /tmp/myscript.lock
}
trap cleanup EXIT ERR

# Lock file to prevent duplicate runs
if [[ -f /tmp/myscript.lock ]]; then
  echo "Script already running"
  exit 1
fi
touch /tmp/myscript.lock

Script Arguments

#!/bin/bash
# Usage: ./deploy.sh staging|production
ENV="${1:-staging}"  # default to staging

case "$ENV" in
  staging)    HOST="staging.example.com" ;;
  production) HOST="prod.example.com" ;;
  *)          echo "Usage: $0 staging|production"; exit 1 ;;
esac

echo "Deploying to $HOST..."

FAQ

What should every Bash script start with?

A shebang line (#!/usr/bin/env bash) and set -euo pipefail so the script stops on errors and unset variables.

How do I run a script?

Make it executable with chmod +x script.sh, then run ./script.sh.