AcademyTerminal Tactics: Survival in the ShellPhase 6: Automatic Sentinels (Automation)

Lesson 2: The Decision Maker (Variables & Logic)

A shell script that just runs commands in order is useful. But a script that can make decisions and repeat actions is powerful. Time to add a brain to your scripts.

Variables

Variables store data for reuse. No let, const, or var — just the name:

#!/bin/bash
NAME="CloudCorp Server"
VERSION=3
echo "Welcome to $NAME v$VERSION"

Rules:

  • No spaces around = (❌ NAME = "test" → ✅ NAME="test").
  • Use $ to read the variable's value.
  • Use "$VAR" (with quotes) to handle spaces safely.

If / Else — Making Decisions

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

if [ "$DISK_USAGE" -gt 80 ]; then
  echo "⚠️ WARNING: Disk usage is at ${DISK_USAGE}%!"
else
  echo "✅ Disk usage is healthy at ${DISK_USAGE}%."
fi

Loops — Repeating Actions

#!/bin/bash
for server in web1 web2 web3 db1; do
  echo "Checking $server..."
  ping -c 1 "$server" > /dev/null 2>&1
  if [ $? -eq 0 ]; then
    echo "  ✅ $server is UP"
  else
    echo "  ❌ $server is DOWN"
  fi
done
  • $? contains the exit code of the last command (0 = success).
booting...

Mission Objective

Create a script that checks the system and reports its status:

  1. Create it: Run touch checker.sh.
  2. Arm it: Make it executable with chmod +x checker.sh.
  3. Deploy it: Run ./checker.sh (we've pre-loaded content for you).

Why This Matters

CI/CD pipelines are essentially sophisticated bash scripts with variables and logic. Jenkins, GitHub Actions, and GitLab CI all rely on the same concepts you just learned.

Mission Control

Create a script with variables

Expected Command

touch checker.sh

Make the script executable

Execute your decision-making script