Skip to content
devops.academy

Module 3: Bash Scripting — The Complete Guide

Goal

Turn the commands you learned in Module 2 into reusable automation. In DevOps, bash is the glue: deploy scripts, CI steps, Docker entrypoints, health checks, and server bootstrap scripts are all bash.


1. Your First Script & How Scripts Run

bash
#!/bin/bash
# deploy.sh — the shebang line above tells Linux which interpreter to use

echo "Starting deployment..."
bash
chmod +x deploy.sh    # make executable
./deploy.sh           # run it

The professional header — use this in EVERY script

bash
#!/bin/bash
set -euo pipefail
  • -e — exit immediately if any command fails (no silently continuing after a failed step!)
  • -u — using an undefined variable is an error (catches typos like $SREVER)
  • -o pipefail — a pipeline fails if any command in it fails, not just the last

Real disaster this prevents: a deploy script where cd /opt/app fails (dir missing) but the script continues and runs rm -rf ./* — in whatever directory you were actually in. set -e stops the script at the failed cd.

Analogy

A script is a recipe written down so any cook — including a tired future you at 3 a.m. — can produce exactly the same dish. The professional header is the kitchen's cardinal rule: stop cooking the moment something burns. Without it, a cook who drops the main ingredient on the floor just keeps following the remaining steps and cheerfully plates an empty dish.


2. Variables

bash
NAME="production"          # NO spaces around = (name = "x" is an error)
echo "Deploying to $NAME"
echo "File: ${NAME}_backup.tar.gz"   # braces when text touches the variable

TODAY=$(date +%F)          # command substitution: capture output
FILE_COUNT=$(ls /opt/app | wc -l)

Quoting rule that separates juniors from seniors: always double-quote variables.

bash
FILE="my report.txt"
rm $FILE      # ✗ runs: rm my report.txt  → tries to delete TWO files
rm "$FILE"    # ✓ deletes "my report.txt"

Differences from other languages: everything is a string by default; variables are global unless declared local inside functions; no spaces around =.

Analogy

Variables are the labelled prep bowls a cook lines up before service — one holds the chopped onions, one holds the sauce. Quoting a variable is putting a lid on the bowl before you carry it: an unquoted $FILE with a space in the name is a lidless bowl that spills into two, and the kitchen ends up seasoning the wrong dish.

Environment variables & script arguments

bash
export APP_ENV=staging     # visible to child processes — how apps get config

# Arguments: ./deploy.sh staging v2.1
ENV=$1                     # first argument
VERSION=$2                 # second
echo "Args count: $#, all args: $@, script name: $0"
EXIT_OF_LAST_CMD=$?        # 0 = success, non-zero = failure

Reading user input

bash
read -p "Which environment? " TARGET_ENV
read -sp "Enter DB password: " DB_PASS   # -s hides typing (secrets)
echo
echo "Deploying to $TARGET_ENV"

Defaults & parameter expansion (very common in Docker entrypoints)

bash
PORT="${PORT:-8080}"           # use $PORT if set, else 8080
: "${API_KEY:?API_KEY must be set}"   # abort with message if missing
FILENAME="backup.tar.gz"
echo "${FILENAME%.tar.gz}"     # strip suffix → "backup"

3. Conditionals

bash
if [[ "$ENV" == "production" ]]; then
    echo "  Production deploy — extra checks"
elif [[ "$ENV" == "staging" ]]; then
    echo "Staging deploy"
else
    echo "Unknown env: $ENV" >&2   # errors go to stderr
    exit 1
fi

Test operators you'll actually use

TestMeaning
[[ -f path ]]file exists
[[ -d path ]]directory exists
[[ -s path ]]file exists and is NOT empty
[[ -r / -w / -x path ]]readable / writable / executable
[[ -z "$var" ]] / [[ -n "$var" ]]string empty / not empty
[[ "$a" == "$b" ]]string equality
(( num > 5 ))arithmetic comparison

Real-world condition patterns

bash
# Check a directory is empty before using it
if [[ -d /opt/app && -z "$(ls -A /opt/app)" ]]; then
    echo "Directory is empty, safe to deploy"
fi

# Don't run as root
if [[ $EUID -eq 0 ]]; then
    echo "Do not run this as root" >&2; exit 1
fi

# Verify a required tool exists
if ! command -v docker &>/dev/null; then
    echo "docker is not installed" >&2; exit 1
fi

# Short-circuit style (idiomatic one-liners)
[[ -f .env ]] && source .env
mkdir -p /var/log/myapp || exit 1

4. Loops

Analogy

A for loop is "do this to every plate coming down the pass"; a while/until loop is "keep stirring until the sauce thickens". The health-check retry loop is exactly that last one: you don't plate the dish on a fixed timer, you keep checking until it's actually ready — or you give up after ten tries and tell the head chef something's wrong.

bash
# Over a list
for server in web1 web2 web3; do
    echo "Pinging $server"; ping -c1 "$server" >/dev/null && echo "OK" || echo "DOWN"
done

# Over files — quote and use globs, never parse ls
for f in /var/log/*.log; do
    echo "$(basename "$f"): $(wc -l < "$f") lines"
done

# C-style / ranges
for i in {1..5}; do echo "attempt $i"; done

# While — retry pattern (real deployment health check)
ATTEMPTS=0
until curl -fsS http://localhost:8080/health >/dev/null; do
    (( ATTEMPTS++ ))
    if (( ATTEMPTS >= 10 )); then
        echo "App failed to become healthy" >&2; exit 1
    fi
    echo "Waiting for app... ($ATTEMPTS/10)"; sleep 3
done
echo "App is healthy ✔"

# Read a file line by line (e.g., a server inventory)
while IFS= read -r host; do
    ssh "$host" 'uptime'
done < servers.txt

5. Arrays & Maps

bash
# Indexed array
SERVERS=("web1.example.com" "web2.example.com" "db1.example.com")
echo "${SERVERS[0]}"          # first
echo "${#SERVERS[@]}"         # count
for s in "${SERVERS[@]}"; do echo "$s"; done   # ALWAYS quote "${arr[@]}"

# Associative array (map) — bash 4+
declare -A PORTS=( [web]=8080 [api]=3000 [db]=5432 )
echo "api runs on ${PORTS[api]}"
for svc in "${!PORTS[@]}"; do
    echo "$svc → ${PORTS[$svc]}"
done

Real use: mapping service→port, env→server list, region→AMI ID in provisioning scripts.


6. Functions

bash
log() {
    echo "[$(date '+%F %T')] $*"
}

backup_db() {
    local db_name=$1                       # local = doesn't leak globally
    local out="/backups/${db_name}_$(date +%F).sql.gz"
    log "Backing up $db_name → $out"
    pg_dump "$db_name" | gzip > "$out" || return 1
    log "Backup complete ($(du -h "$out" | cut -f1))"
}

backup_db "users_db" || { log "BACKUP FAILED"; exit 1; }

Rules: define before use; arguments come in as $1 $2...; return sets an exit code (0=success), output is returned by echo + command substitution: size=$(get_size "$file").

Analogy

A function is a sub-recipe on its own card — "make the roux" — that the main recipe calls whenever it needs one, instead of re-writing the steps every time. local keeps that card's scratch ingredients on its own bench, so a variable named temp in the roux never contaminates the temp on the main line. And trap cleanup EXIT is the rule "whatever happens, wipe down the station before you leave" — it runs even if the kitchen catches fire mid-service.

Error handling with trap (cleanup that always runs)

bash
TMPDIR=$(mktemp -d)
cleanup() { rm -rf "$TMPDIR"; }
trap cleanup EXIT        # runs on ANY exit — success, failure, Ctrl+C

7. Subshells

Commands in (...) run in an isolated child shell — its cd and variable changes don't affect your script:

bash
# Build in another directory without losing your place
(cd /opt/app/build && make all)
pwd    # still where you were

# vs { ...; } which groups commands in the SAME shell
{ echo "a"; echo "b"; } > combined.txt

Gotcha: pipes create subshells — variables set inside ... | while read vanish afterwards. Fix with redirection: while read -r line; do ...; done < file.


8. Real-World Script Walkthrough — A Production-Style Deploy Script

This combines everything. Read it slowly; every line uses a concept from above.

Analogy

This deploy script is the full banquet recipe: mise en place at the top (config and pre-flight checks), cook the courses in order (fetch, switch, health-check), and — crucially — a written "if the main course comes back to the kitchen, re-plate last night's proven dish" step. A deploy with automatic rollback is a recipe that already knows how to serve yesterday's batch the instant tonight's tastes wrong.

bash
#!/bin/bash
set -euo pipefail

# ---------- config ----------
APP_NAME="myapp"
APP_DIR="/opt/${APP_NAME}"
RELEASES_DIR="${APP_DIR}/releases"
KEEP_RELEASES=5
HEALTH_URL="http://localhost:8080/health"

log()  { echo "[$(date '+%F %T')] $*"; }
die()  { log "ERROR: $*" >&2; exit 1; }

# ---------- pre-flight checks ----------
[[ $# -eq 1 ]] || die "Usage: $0 <version>   e.g. $0 v2.3.1"
VERSION=$1
command -v curl >/dev/null || die "curl not installed"
[[ -d "$APP_DIR" ]]        || die "$APP_DIR does not exist"

RELEASE_PATH="${RELEASES_DIR}/${VERSION}"

# ---------- fetch release ----------
log "Deploying ${APP_NAME} ${VERSION}"
mkdir -p "$RELEASE_PATH"
curl -fsSL "https://releases.example.com/${APP_NAME}/${VERSION}.tar.gz" \
    | tar -xz -C "$RELEASE_PATH" \
    || die "Download/extract failed"

# ---------- atomic switch via symlink ----------
PREVIOUS=$(readlink -f "${APP_DIR}/current" 2>/dev/null || true)
ln -sfn "$RELEASE_PATH" "${APP_DIR}/current"
sudo systemctl restart "$APP_NAME"

# ---------- health check with rollback ----------
for i in {1..10}; do
    if curl -fsS "$HEALTH_URL" >/dev/null; then
        log "Health check passed ✔"
        # keep only the last N releases
        ls -1dt "${RELEASES_DIR}"/* | tail -n +$((KEEP_RELEASES+1)) | xargs -r rm -rf
        log "Deployment of ${VERSION} complete."
        exit 0
    fi
    log "Waiting for health... ($i/10)"; sleep 3
done

# ---------- rollback ----------
log "Health check FAILED — rolling back"
[[ -n "$PREVIOUS" ]] && ln -sfn "$PREVIOUS" "${APP_DIR}/current" && sudo systemctl restart "$APP_NAME"
die "Deployment failed; rolled back to previous release"

This symlink-switch + health-check + rollback pattern is exactly what tools like Capistrano formalize, and what you'll later rebuild in CI/CD pipelines (Module 6).


9. Other Scripts You'll Write in Real Jobs

Backup with retention:

bash
#!/bin/bash
set -euo pipefail
BACKUP_DIR=/backups
mkdir -p "$BACKUP_DIR"
tar -czf "${BACKUP_DIR}/app_$(date +%F).tar.gz" /opt/app/data
find "$BACKUP_DIR" -name "app_*.tar.gz" -mtime +14 -delete   # keep 14 days

Disk-space alert (cron every 5 min):

bash
#!/bin/bash
USAGE=$(df / --output=pcent | tail -1 | tr -dc '0-9')
if (( USAGE > 85 )); then
    curl -s -X POST "$SLACK_WEBHOOK" \
         -d "{\"text\":\" Disk at ${USAGE}% on $(hostname)\"}"
fi

Log sweep across servers:

bash
for host in $(cat servers.txt); do
    echo "=== $host ==="
    ssh "$host" "grep -c 'ERROR' /var/log/app.log || true"
done

10. Debugging & Quality

bash
bash -n script.sh     # syntax check without running
bash -x script.sh     # trace: prints every command as it executes
# or inside a script:  set -x  ...  set +x  around the tricky section

ShellCheck (apt install shellcheck, or shellcheck.net) is a linter that catches unquoted variables, useless cats, broken conditions. Professionals run it in CI on every script. Make it a habit from day one.

Analogy

ShellCheck is the health inspector who reads your recipe before anyone eats it and points at every lidless bowl and cross-contamination risk. set -euo pipefail is the kitchen rule "stop cooking the instant anything burns" — no quietly serving a dish that failed halfway. Treat both as your reviewer, not your enemy: they catch the mistakes that would otherwise reach the customer.

Style rules: UPPER_CASE for env/config constants, lower_case for locals; prefer [[ ]] over [ ]; prefer $(...) over backticks; keep scripts under ~200 lines — beyond that, reach for Python or Ansible.


11. Hands-On Project (Do This)

  1. Write sysinfo.sh: prints hostname, uptime, disk %, memory, top 3 CPU processes — nicely formatted with a log() function.
  2. Write cleanup.sh <dir> <days>: validates arguments, refuses to run on /, deletes files older than N days, prints how many were removed.
  3. Write healthcheck.sh: loops over an array of URLs, curls each, prints ✔/✘, exits non-zero if any fail (this becomes a CI smoke test later).
  4. Write the deploy script from section 8 against a dummy app; test the rollback path by making the health check fail.
  5. Run ShellCheck on all four and fix every warning.

12. Self-Check Questions

  • What do set -e, -u, -o pipefail each protect you from?
  • Why must variables be double-quoted? Show a failure case.
  • How do you retry a command up to N times with a sleep between attempts?
  • Difference between (cd /tmp && ls) and cd /tmp && ls?
  • Why does echo $? show 0 after a failed command in a pipe without pipefail?
  • When should you stop using bash and switch to Python/Ansible?

Next → Module 11: Python for DevOps (the recommended path slots Python in here — bash for gluing commands, Python the moment you need real logic).