TExcelTAD

Idempotent Scripts

An operation is idempotent when doing it twice has the same effect as doing it once. For automation this is the property that matters most: setup scripts are re-run after a partial failure, provisioning runs on every boot, CI retries a flaky job, and someone runs the script "just to be sure". A script that is not idempotent turns each of those into a new problem. Tools like Ansible, Terraform and Kubernetes are built around the same idea of converging to a desired state; this lesson applies it to plain Bash.

A script that breaks on the second run

bash · try it yourself
cat > setup.sh <<'SCRIPT'
set -euo pipefail
mkdir app
echo "export APP_HOME=$PWD/app" >> profile
cp -R defaults app/config
ln -s app/config current
echo "setup done"
SCRIPT
mkdir defaults && echo "port=8080" > defaults/app.conf
bash setup.sh; echo "-> run 1: $?"
bash setup.sh; echo "-> run 2: $?"
cat profile
setup done
-> run 1: 0
mkdir: cannot create directory ‘app’: File exists
-> run 2: 1
export APP_HOME=/home/learner/app

The second run stopped at mkdir. Had it got further, profile would have the export line twice, cp -R would create app/config/defaults, and ln -s would fail because current exists. Every line assumed it was the first run.

The idempotent version

Each step now checks the current state and only acts when the state is wrong. It also reports what it did, so a second run that changes nothing is visibly a no-op:

bash · try it yourself
cat > setup.sh <<'SCRIPT'
set -euo pipefail
changed=0
note() { printf '%-8s %s\n' "$1" "$2"; [ "$1" = ok ] || changed=$((changed + 1)); }

ensure_dir() {
  if [ -d "$1" ]; then note ok "dir $1"; else mkdir -p "$1"; note created "dir $1"; fi
}
ensure_line() {   # ensure_line FILE LINE: append LINE unless it is already there
  touch "$1"
  if grep -qxF -- "$2" "$1"; then note ok "line in $1"; else echo "$2" >> "$1"; note added "line in $1"; fi
}
ensure_file() {   # ensure_file SRC DEST: copy only when content differs
  if cmp -s "$1" "$2"; then note ok "file $2"; else install -m 644 "$1" "$2"; note updated "file $2"; fi
}
ensure_link() {   # ensure_link TARGET NAME
  if [ "$(readlink "$2" 2>/dev/null)" = "$1" ]; then note ok "link $2"; else ln -sfn "$1" "$2"; note linked "link $2 -> $1"; fi
}

ensure_dir app/config
ensure_line profile "export APP_HOME=$PWD/app"
ensure_file defaults/app.conf app/config/app.conf
ensure_link app/config current
echo "$changed change(s)"
SCRIPT
mkdir defaults && echo "port=8080" > defaults/app.conf
echo "== run 1";  bash setup.sh
echo "== run 2";  bash setup.sh
echo "port=9090" > defaults/app.conf
echo "== run 3 (config changed)"; bash setup.sh
cat profile app/config/app.conf
== run 1
created  dir app/config
added    line in profile
updated  file app/config/app.conf
linked   link current -> app/config
4 change(s)
== run 2
ok       dir app/config
ok       line in profile
ok       file app/config/app.conf
ok       link current
0 change(s)
== run 3 (config changed)
ok       dir app/config
ok       line in profile
updated  file app/config/app.conf
ok       link current
1 change(s)
export APP_HOME=/home/learner/app
port=9090

The tools behind each step:

Step Not idempotent Idempotent
directory mkdir dir mkdir -p dir
line in a file echo line >> file `grep -qxF -- "$line" file
copy a file cp src dest (always writes, changes mtime) `cmp -s src dest
symlink ln -s target name ln -sfn target name (-n: replace a link to a directory instead of creating one inside it)
delete rm file rm -f file
user, package, service useradd x `id x >/dev/null 2>&1

grep -qxF matches the whole line (-x) as a fixed string (-F): without them, port=80 would "already be there" because it is part of port=8080, and dots in a value would act as regex wildcards.

Report changes, act on changes

Counting changes is not decoration. It lets the script do expensive or disruptive follow-up work, such as reloading nginx or restarting a service, only when something actually changed, and it lets CI or a configuration run say "0 changes" on the second pass. That second-pass check is the simplest test of idempotency there is: run the script twice in a fresh container and assert the second run reports no changes.

bash
if [ "$changed" -gt 0 ]; then
  nginx -t && systemctl reload nginx
fi

Idempotency vs "run once"

Some steps cannot be made naturally idempotent: a database migration, sending an email, creating a release. For those, record that the step happened and check the record next time, ideally in the system you changed (a schema_migrations table, a Git tag, a release that already exists in the API) rather than in a local marker file that a new machine will not have.

Test yourself

What makes an operation idempotent?

  1. It runs quickly
  2. Running it twice has the same effect as running it once
  3. It never fails
  4. It uses set -e

Why use grep -qxF -- "$line" file rather than grep -q "$line" file to check for a line?

  1. It is faster
  2. -x matches the whole line and -F treats the text literally, so partial matches and regex characters do not cause false positives
  3. -q does not work alone
  4. There is no difference

Why compare files with cmp -s before copying?

  1. cp cannot overwrite files
  2. So the script only writes, and only reports a change (and triggers reloads), when the content really differs
  3. cmp fixes permissions
  4. To make the copy atomic