Self-updating shell scripts without the footguns

HaltOS is mostly a shell script, and sudo haltos update replaces that script while it runs. That is more dangerous than it sounds. These are the patterns that make it safe.
Bash reads your script while it runs
Bash does not load a script into memory before running it. It reads as it goes. If git pull rewrites the file halfway through, bash carries on reading at the same byte offset, now in the middle of the new file, and runs whatever it finds there.
The fix is to never return to the old file after the update. Hand over to the new copy with exec, which replaces the running process:
git -C "$HERE" checkout -q "v$target"
# The checkout rewrote this script, so the rest runs in the new copy.
exec "$HERE/install.sh" finish-update "$old"
Follow releases, not the main branch
Pulling main gives every server whatever was merged five minutes ago. Releases are safer: servers check out the newest version tag, and only people who ask for it follow main.
target=$(git tag -l 'v*' | sed 's/^v//' | sort -V | tail -1)
sort -V matters: plain sorting puts 1.10.0 before 1.9.0.
Check for updates cheaply
git ls-remote lists the remote's tags without downloading anything. A daily systemd timer runs it and writes the newest version to a file, and the SSH login banner compares it with the installed version:
git ls-remote --tags --refs origin 'v*' | sed 's|.*refs/tags/v||' | sort -V | tail -1
Logging in never waits on the network, and you still find out about a new release within a day.
Refuse to clobber local work
Before switching versions, the update checks that the checkout has no local changes and stops with a clear message if it does. An update that silently throws away someone's edits is worse than no update.
Releasing is one command
On the other side, tools/release.sh 1.1.0 checks that the VERSION file and the changelog agree, tags and pushes, and a GitHub Actions workflow publishes the release. The whole flow is in the HaltOS repository.
All posts Next: Run several Claude Code agents in parallel with git worktrees