Ravindra BagaleCourses & study guides मराठी

Chapter 5: Bash Scripting for Automation

DevOps

5.11 Lab — health check script with dry-run

Why: the problem

Think of Swiggy again, at the end of this chapter. You now know variables, quotes, if and loops, safe reruns, cron, secrets, arguments, functions and debugging. Real work needs all of them at once. A common real task is a health check that restarts an app only when it is truly down, logs every run, has a dry-run mode for safe testing, and runs from cron every five minutes. This lab builds exactly that, step by step, using the lib.sh from lesson 5.9. Below you will first see the full worked script and three ways to run it. Then the lab box lists the steps for you to do on your own machine.

What we will build

You will build health_restart.sh. It reads APP_URL from the environment, checks it with curl and retries, restarts the service only when needed, logs to ~/badge-api-logs/, supports --dry-run and --help, and returns clear exit codes. You will test it healthy, with the app stopped in dry-run mode, and with a real restart. Then you will schedule it with cron using flock.

What: every term in plain English

  • Health endpoint — A URL like /health that returns 200 when the app is fine.
  • Dry run — Print what would be done without doing it.
  • Restart command — The exact command that restarts your service, like docker restart menu-api or systemctl restart menu-api.
  • Log line — One line per run with time, status and action.
  • Exit codes — 0 healthy, 1 still down after restart, 2 bad usage, 3 down in dry run.
  • flock — A lock so two cron runs never overlap.
  • Lab app — A small app in Docker, so you can stop and start it safely.
  • Runbook — A note on what the script does and how to undo it.
Start a lab app Write the script Run healthy Stop the app Dry run Real restart Schedule it
Check, retry, restart, log, schedule

How: step by step

  1. Start a lab app

    docker run -d --name menu-api -p 3000:80 nginx:alpine && curl -sI localhost:3000 | head -1
    

    What it does: A stand-in for your app.

    Output

    HTTP/1.1 200 OK
    
  2. Write the script

    nano ~/bash-lab/health_restart.sh
    

    What it does: Paste Example 1.

    Output

    (file saved)
    
  3. Run healthy

    bash ~/bash-lab/health_restart.sh; echo "exit=$?"
    

    What it does: Exit 0 and one log line.

    Output

    OK http://localhost:3000/
    exit=0
    
  4. Stop the app

    docker stop menu-api
    

    What it does: Simulate an outage.

    Output

    menu-api
    
  5. Dry run

    bash ~/bash-lab/health_restart.sh --dry-run; echo "exit=$?"
    

    What it does: Says what it would restart.

    Output

    DOWN: would run: docker restart menu-api
    exit=3
    
  6. Real restart

    bash ~/bash-lab/health_restart.sh; echo "exit=$?"
    

    What it does: Restarts and checks again.

    Output

    DOWN: restarting menu-api
    RECOVERED
    exit=0
    
  7. Schedule it

    crontab -e  (add the line from Example 3)
    

    What it does: Runs every 5 minutes with a lock.

    Output

    crontab: installing new crontab
    

Example 1: The full health and restart script

Stack. Bash, curl, Docker

Goal. The full health and restart script.

health_restart.sh

#!/usr/bin/env bash
set -euo pipefail
. "$(dirname "$0")/lib.sh"
APP_URL="${APP_URL:-http://localhost:3000/}"
SERVICE="${SERVICE:-menu-api}"
RESTART_CMD="${RESTART_CMD:-docker restart $SERVICE}"
LOG_DIR="$HOME/badge-api-logs"
DRY=0
case "${1:-}" in
  --dry-run) DRY=1 ;;
  -h|--help) echo "Usage: health_restart.sh [--dry-run]  (env: APP_URL SERVICE RESTART_CMD)"; exit 0 ;;
  "") ;;
  *) echo "unknown option: $1"; exit 2 ;;
esac
mkdir -p "$LOG_DIR"
record() { echo "$(date '+%F %T %Z') $*" >> "$LOG_DIR/health.log"; echo "$*"; }
healthy() {
  local i
  for i in 1 2 3; do
    curl -fsS --max-time 3 -o /dev/null "$APP_URL" && return 0
    sleep 2
  done
  return 1
}
if healthy; then record "OK $APP_URL"; exit 0; fi
if [ "$DRY" -eq 1 ]; then record "DOWN: would run: $RESTART_CMD"; exit 3; fi
record "DOWN: restarting $SERVICE"
$RESTART_CMD >/dev/null
sleep 2
if healthy; then record "RECOVERED"; exit 0; else record "STILL DOWN after restart"; exit 1; fi

What each line does

  • . "$(dirname "$0")/lib.sh" — Loads log, die and need from lesson 5.9.
  • APP_URL / SERVICE / RESTART_CMD — Settings from the environment with safe defaults.
  • case "${1:-}" — Handles --dry-run, --help, nothing, or a bad option.
  • record() — Writes a timestamped line to the log and also prints it.
  • healthy() — Three tries, two seconds apart. Returns 0 or 1.
  • exit 0 / 1 / 2 / 3 — Clear meaning for cron, Jenkins or monitoring.

Green output

$ bash health_restart.sh
OK http://localhost:3000/
$ docker stop menu-api >/dev/null; bash health_restart.sh --dry-run; echo "exit=$?"
DOWN: would run: docker restart menu-api
exit=3
$ bash health_restart.sh; echo "exit=$?"
DOWN: restarting menu-api
RECOVERED
exit=0
$ tail -3 ~/badge-api-logs/health.log
2026-10-25 13:01:10 IST OK http://localhost:3000/
2026-10-25 13:02:05 IST DOWN: would run: docker restart menu-api
2026-10-25 13:02:30 IST DOWN: restarting menu-api

Expected result. The script handles healthy, dry-run and real-restart cases, and logs each one.

Example 2: Use the same script for a systemd service on a VM

Stack. Bash, systemd, sudo

Goal. Use the same script for a systemd service on a VM.

run on a VM

export APP_URL=http://127.0.0.1:8080/health
export SERVICE=menu-api
export RESTART_CMD="sudo systemctl restart menu-api"
bash ~/bash-lab/health_restart.sh --dry-run
bash ~/bash-lab/health_restart.sh

/etc/sudoers.d/menu-api (edit with sudo visudo -f)

ravi ALL=(root) NOPASSWD: /usr/bin/systemctl restart menu-api

What each line does

  • APP_URL — Your VM app health URL.
  • RESTART_CMD="sudo systemctl restart menu-api" — Restart the systemd unit instead of a container.
  • sudoers line — Lets ravi run only this one restart command without a password. Nothing else.
  • visudo -f — Edits sudoers safely and checks the syntax before saving.
  • Same script — Only environment values changed.

Green output

$ bash health_restart.sh --dry-run
DOWN: would run: sudo systemctl restart menu-api
$ bash health_restart.sh
DOWN: restarting menu-api
RECOVERED
$ systemctl is-active menu-api
active

Expected result. One script works for Docker and systemd. Change settings, not code.

Example 3: Schedule it safely with cron and flock, then remove it

Stack. cron, flock

Goal. Schedule it safely with cron and flock, then remove it.

crontab line

CRON_TZ=Asia/Kolkata
*/5 * * * * /usr/bin/flock -n /tmp/health.lock /usr/bin/bash /home/ravi/bash-lab/health_restart.sh >> /home/ravi/badge-api-logs/cron.log 2>&1

remove-cron.sh

#!/usr/bin/env bash
set -euo pipefail
crontab -l | grep -v health_restart.sh | crontab -
crontab -l || echo "no cron jobs left"

What each line does

  • CRON_TZ=Asia/Kolkata — Times in this crontab are read in IST.
  • */5 * * * * — Every 5 minutes.
  • flock -n /tmp/health.lock — Skip if the previous run is still going.
  • >> cron.log 2>&1 — Keep output and errors.
  • remove-cron.sh — Removes only the health line when the lab ends.

Green output

$ tail -2 ~/badge-api-logs/cron.log
OK http://localhost:3000/
OK http://localhost:3000/
$ bash remove-cron.sh
no crontab for ravi
no cron jobs left

Expected result. The check ran every 5 minutes and was removed cleanly at the end of the lab.

Verify: did it work?

  1. Log has all three cases

    grep -cE "OK|would run|RECOVERED" ~/badge-api-logs/health.log
    

    What it does: At least three lines.

    Output

    3
    
  2. ShellCheck clean

    shellcheck ~/bash-lab/health_restart.sh ~/bash-lab/lib.sh && echo clean
    

    What it does: No warnings.

    Output

    clean
    

When it is red 1

lib.sh: No such file or directory under cron

Cause. lib.sh is not next to the script.

Fix, step by step

  1. Keep lib.sh in the same folder.
  2. The script loads it with dirname "$0".

When it is red 2

STILL DOWN after restart

Cause. The app crashes on start, or the URL is wrong.

Fix, step by step

  1. Check docker logs menu-api.
  2. curl the URL by hand.
  3. Fix the app; do not loop restarts.

When it is red 3

sudo: a password is required (cron)

Cause. sudoers line missing or wrong command path.

Fix, step by step

  1. Use visudo -f and the exact path from command -v systemctl.

Cleanup

  1. Stop the lab app

    docker rm -f menu-api
    

    What it does: Clean the lab.

    Output

    menu-api
    
  2. Remove the cron line

    bash remove-cron.sh
    

    What it does: No leftover jobs.

    Output

    no cron jobs left
    

Ravindra Bagale's Tip

Finish the lab: healthy, dry-run, then a real restart. Then attach cron and remove it again. Keep that in mind!

Practice tasks

Easy Healthy run

Why: Start from green.

What to do: Run the script with the app up.

How:
  1. Read the log.

Check: OK line logged.

Medium Dry run and restart

Why: Practice both safe and real paths.

What to do: Stop the app, dry-run, then restart.

How:
  1. Check exit codes.

Check: Exit 3 then exit 0.

Hard Cron with lock

Why: Automation must not pile up.

What to do: Schedule with flock and remove after an hour.

How:
  1. Use remove-cron.sh.

Check: Cron log has lines, crontab clean at end.

Easy Say the health check lab in two lines

Why: If you can say it simply, you understand it. Juniors and interviewers both want the short version first.

What to do: Write two short lines about the health check lab for a fresher who knows only basic Linux commands.

How:
  1. Write the problem it solves.
  2. Write the one command or line of script you use for it.
  3. Read it aloud to a friend.

Check: A fresher understands it without asking a question.

Easy Make a safe lab folder

Why: Scripts can delete or overwrite files. Practice in a folder you can throw away.

What to do: Create a lab folder and work only inside it.

How:
  1. mkdir -p ~/bash-lab && cd ~/bash-lab
  2. Run every script in this lesson from here with bash name.sh
  3. When done, rm -rf ~/bash-lab only after checking the path with pwd.

Check: All lab files live in ~/bash-lab and nothing else changed.

Medium Run it on a second machine

Why: A script that works only on your laptop is not finished. Servers have a different PATH, user and shell.

What to do: Copy the script to an Ubuntu EC2 or a Docker ubuntu container and run it there.

How:
  1. docker run --rm -it -v "$PWD":/lab -w /lab ubuntu:24.04 bash
  2. Run the script.
  3. Note anything that changed.

Check: Same output on both machines, or you fixed the difference.

Medium Break it on purpose

Why: You must know the red message by face. In a real outage there is no time to read slowly.

What to do: Cause one error from the "When it is red" part of this lesson and fix it.

How:
  1. Follow the error section.
  2. Copy the exact message into your notes.
  3. Write the fix in one line.

Check: You fixed it using only the steps, without searching the web.

Medium Check it with ShellCheck

Why: ShellCheck finds quoting bugs and mistakes before they hit a server.

What to do: Run ShellCheck on every script from this lesson.

How:
  1. sudo apt install -y shellcheck
  2. shellcheck name.sh
  3. Fix each warning and run again.

Check: ShellCheck prints nothing.

Hard Explain it like an interview

Why: Interviewers want real stories, not definitions.

What to do: Record a 60 second answer about this lesson.

How:
  1. Say the problem, the script line, and one error you hit.

Check: Your answer has a real command and a real error message.

Hard Draw the flow top to bottom

Why: A drawing shows the order of checks and what happens on failure.

What to do: Draw this lesson script as boxes from top to bottom.

How:
  1. Start at the first line, show each if as a split, end at the exit code.

Check: Each box matches a real line in the script.

Homework: try at home

Try at home

At home, point health_restart.sh at a real app you run (a Node, Python or Docker app). Test healthy, dry-run and real restart. Keep the log for one day with cron, then remove the cron line.

Recap

  • The lab joins every skill from this chapter into one tool.
  • Settings come from the environment with safe defaults.
  • Retry before restart, and log every run.
  • --dry-run and clear exit codes make it safe to test.
  • Schedule with cron and flock, and remove test jobs after.

FAQ

Should I use this in production?

For small setups, yes. At scale, use systemd Restart=, Kubernetes probes or monitoring tools.

Why not restart on every failure?

Restart loops hide real bugs and drop users.

Can it send an alert?

Yes, add a curl to a Slack webhook stored as a secret.

Why log to a file and print?

The file is for history; printing is for cron logs and humans.

What next after Bash?

Docker in the next chapters, and later Ansible for many servers.

Interview questions

  1. Walk me through a health check script you wrote.

    It reads the URL from env, retries curl three times, restarts only on real failure, checks again, logs each run and returns clear exit codes. It has --dry-run and runs from cron with flock.

  2. How do you avoid restart loops?

    Retry before restart, restart once per run, and alert if still down instead of looping.

  3. How do you give a script limited sudo rights?

    A sudoers.d line allowing only the exact restart command.

  4. Why use exit codes in such a script?

    So cron, Jenkins or monitoring can react to success or failure.

  5. How would you do this in Kubernetes?

    Liveness and readiness probes replace the script.

Quick quiz

Q1. What exit code does the script give when down in dry run?

3.

Q2. Why retry three times before restarting?

To avoid restarts on short blips.

Q3. Where does the script log?

~/badge-api-logs/health.log

Q4. What does flock -n stop?

Overlapping runs.

Q5. How do you switch from Docker to systemd?

Change RESTART_CMD, not the code.

Lab

Build health_restart.sh for your badge API hello API (local Docker/Node/Python or a small service on your VM).

  1. Shebang + set -euo pipefail.
  2. Default APP_URL to your health endpoint (environment can override).
  3. curl -fsS the URL; on success print OK and exit 0.
  4. On failure: if --dry-run was passed, print what you would restart and exit 1; else restart the service you actually use in the lab, wait two seconds, curl again.
  5. Log a one-line timestamp result under ~/badge-api-logs/ (mkdir -p first).
  6. Run once healthy, once with the app stopped (dry-run), once with a real restart if safe.
  7. Optional: add a cron line that runs every five minutes with log redirect — remove the cron entry when the lab ends.

Practice task

List three reasons a script that works in your SSH session can fail under cron. Fix each with one concrete habit (absolute path, env, logging).

In short

  • Bash scripts turn repeated ops into a file: shebang, set -euo pipefail, clear exit codes.
  • Variables + quotes; if / loops for health; restart only when needed.
  • Aim for twice-safe scripts (mkdir -p, check before install).
  • Cron needs absolute paths and logs; interactive PATH is not guaranteed.
  • Secrets stay in the environment / secret stores — never in committed scripts.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards