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).
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.Beginner