Interview Prep/Shell Scripting/Functions, exit codes, strict mode and traps

How do you write a script that is safe to run twice (idempotent)?

IntermediateConceptFunctions, exit codes, strict mode and traps
Answer

Check state before changing it, and make every step converge to the desired state:

id -u deploy &>/dev/null || useradd --system --create-home deploy
mkdir -p /srv/app/releases
grep -qxF 'vm.swappiness=10' /etc/sysctl.d/99-app.conf 2>/dev/null ||
  echo 'vm.swappiness=10' >> /etc/sysctl.d/99-app.conf
ln -sfn "/srv/app/releases/$release" /srv/app/current
systemctl enable --now app.service

Prefer declarative commands (mkdir -p, ln -sfn, install -d, systemctl enable --now) over imperative ones that fail or duplicate on rerun (mkdir, >> without a check, useradd without a check).

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Functions, exit codes, strict mode and traps