Ravindra BagaleCourses & study guides

Chapter 5: Bash Scripting for Automation

5.5 Idempotent-ish habits — check before install

Perfect mathematical idempotence is a big word. In junior scripts, aim for: safe to run twice.

Bad habit Better habit
Always mkdir and ignore errors blindly mkdir -p (creates only if needed)
Always download a tool Check command -v tool first
Append to a config forever Grep for a marker line before append
#!/usr/bin/env bash
set -euo pipefail

if ! command -v curl >/dev/null 2>&1; then
  echo "curl missing — install it with your OS package manager, then re-run"
  exit 1
fi

mkdir -p "$HOME/badge-api-logs"

Why. CI and cron will re-run your script. Scripts that explode on the second run create noise and false incidents.

Practice task

Rewrite a reckless mkdir ~/bin (fails if exists) into a twice-safe version. One line is enough.