Shell Automation
What to Automate
Automation has a cost: it must be written, reviewed, tested and maintained. Automate tasks that are frequent, error-prone, urgent (needed during incidents) or that must be done identically on many machines.
Bash or Python?
| Prefer Bash when | Prefer Python when |
|---|---|
| The script mostly runs other commands and connects them with pipes. | There is real logic: data structures, parsing JSON or YAML, retries, error handling. |
| It is short — up to roughly a hundred lines. | It is growing, or needs tests and reuse as a module. |
| It must run on minimal systems with nothing extra installed. | It calls HTTP APIs or cloud SDKs. |
Both belong in version control, with a short header explaining purpose, usage and owner. A script that only exists in someone's home directory is a single point of failure.
Climb the Automation Ladder
Not every task should jump straight to full automation. A practical progression is: a documented manual procedure, then a script a person runs and watches, then a script run on a schedule or by an alert, and finally self-healing behavior built into the platform. Each step builds confidence for the next.
Robust Bash Scripts
By default, Bash keeps going after a failed command, treats unset variables as empty strings, and hides failures inside pipelines. For operational scripts, those defaults are dangerous: rm -rf "$DIR/"* with an unset DIR is a classic disaster.
Start with Strict Mode
#!/usr/bin/env bash
# disk-check.sh: warn when any local filesystem is fuller than a threshold.
# Usage: disk-check.sh [THRESHOLD_PERCENT] (default 85)
set -euo pipefail # exit on error, on unset variables, and on pipeline failures
IFS=$'\n\t' # split words only on newlines and tabs
readonly THRESHOLD="${1:-85}"
status=0
log() { printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >&2; }
# GNU df (Linux): choose the columns and put the mount point last, so a mount point
# containing spaces stays intact; read assigns the rest of the line to the last name.
# IFS=' ' applies to this read only, since the columns are separated by spaces.
while IFS=' ' read -r pct avail mount; do
use="${pct%\%}" # strip the trailing % sign
if (( use >= THRESHOLD )); then
log "WARN ${mount} is ${use}% full (${avail} KiB free)"
status=1
fi
done < <(df -k --output=pcent,avail,target -x tmpfs -x devtmpfs | tail -n +2)
exit "$status"
Exit codes are the interface of a script: 0 means success and anything else means failure, so schedulers and monitoring systems can react. Write log messages to standard error and data to standard output, so the output can be piped into other tools.
Clean Up with Traps
Scripts that create temporary files or take locks must release them even when they fail. A trap on EXIT runs on success, error and most signals:
workdir="$(mktemp -d)"
trap 'rm -rf -- "$workdir"' EXIT # always removed, however the script ends
# Prevent two copies of the script running at once (Linux util-linux flock).
exec 9>/var/lock/nightly-report.lock
flock -n 9 || { echo "another run is in progress" >&2; exit 1; }
Lint Every Script
ShellCheck finds unquoted variables, broken conditionals and portability problems before they reach production. Run it in CI on every shell file, just like a compiler warning: shellcheck scripts/*.sh.
Idempotent and Safe Operations
An operation is idempotent if running it twice has the same effect as running it once. Idempotent scripts can be retried after a failure and scheduled without fear of duplicates, which makes them the foundation of reliable automation.
Check Before You Change
# Not idempotent: a second run appends a duplicate line.
echo "vm.swappiness = 10" >> /etc/sysctl.d/99-tuning.conf
# Idempotent: write the desired state; the result is the same on every run.
printf 'vm.swappiness = 10\n' > /etc/sysctl.d/99-tuning.conf
# Idempotent: create only if missing; -p does not fail when it already exists.
mkdir -p /srv/app/releases
id deploy &>/dev/null || useradd --system --create-home deploy
Describe the desired state rather than the steps to reach it. When this pattern spreads across many files and machines, it is time to move to a configuration management or infrastructure-as-code tool — see Infrastructure as Code.
Offer a Dry Run
Destructive scripts should support a mode that prints what would happen without doing it, and should default to it when the blast radius is large. Ask for explicit confirmation, or require a flag such as --apply, before deleting data or touching many hosts.
Python for Operations
Python's standard library covers most operational needs — files, processes, HTTP, JSON, logging, argument parsing — so a script can stay dependency-free and run anywhere Python 3 is installed.
A Health-Check Script
#!/usr/bin/env python3
"""check_endpoints.py: probe HTTP health endpoints and report failures.
Usage: check_endpoints.py URL [URL ...] [--timeout SECONDS]
Exit status is the number of failed endpoints (0 means all healthy).
"""
import argparse
import logging
import sys
import time
import urllib.request
log = logging.getLogger("check_endpoints")
def probe(url: str, timeout: float) -> bool:
start = time.monotonic()
try:
with urllib.request.urlopen(url, timeout=timeout) as resp:
ok = 200 <= resp.status < 300
log.info("%s %s in %.0f ms", url, resp.status, (time.monotonic() - start) * 1000)
return ok
except OSError as exc: # covers DNS, refused, timeout and HTTP errors
log.error("%s failed: %s", url, exc)
return False
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("urls", nargs="+")
parser.add_argument("--timeout", type=float, default=5.0)
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
return sum(not probe(url, args.timeout) for url in args.urls)
if __name__ == "__main__":
sys.exit(main())
Run Commands Safely
When Python must call system tools, use subprocess.run with a list of arguments rather than a shell string. Arguments are then passed directly to the program, so file names with spaces or shell metacharacters cannot inject commands:
import subprocess
# "is-active" exits non-zero for a stopped service, which is an answer, not an error,
# so check=False; use check=True when any non-zero exit should raise CalledProcessError.
result = subprocess.run(
["systemctl", "is-active", "nginx"],
capture_output=True, text=True, check=False,
)
print(result.returncode, result.stdout.strip())
Scheduling and Running Automation
A script becomes automation when something other than a person starts it, and when its failures reach someone who can act.
Cron and systemd Timers
Cron is available everywhere and is fine for simple jobs. On systemd-based Linux, timers add logging to the journal, dependency handling, randomized delays to avoid load spikes, and catch-up runs after downtime:
# /etc/systemd/system/disk-check.service
[Unit]
Description=Warn about full filesystems
[Service]
Type=oneshot
ExecStart=/usr/local/bin/disk-check.sh 85
# /etc/systemd/system/disk-check.timer
[Unit]
Description=Run disk-check every 15 minutes
[Timer]
OnCalendar=*:0/15
RandomizedDelaySec=60
Persistent=true
[Install]
WantedBy=timers.target
Enable it with systemctl enable --now disk-check.timer, list schedules with systemctl list-timers, and read output with journalctl -u disk-check.service.
Make Job Failures Visible
A scheduled job that fails silently is worse than no job, because everyone believes it works. Alert on non-zero exit codes, and also on missing runs: a “dead man's switch” check that expects a heartbeat after each successful run catches jobs that stopped being scheduled at all. Keep logs with timestamps in UTC so they line up with other systems during an investigation.
Practice Lab
Use a Linux virtual machine, WSL2, or a container where you have root access.
Harden a Bash Script
- Write
disk-check.shfrom this lesson, run it with thresholds of 99 and 1, and check the exit code each time withecho $?. - Run ShellCheck on it and fix every warning.
- Add a lock with
flock, start two copies at once, and confirm the second one refuses to run.
Schedule and Observe
- Install the script as a systemd service and timer that runs every five minutes.
- Make it fail by setting the threshold to 1, and find the failure in
journalctl. - Write the Python health checker, point it at one working and one broken URL, and wire its exit status into the same timer pattern.