Build a Deployment Automation Script
Copying files to a server by hand works until the day a copy is interrupted, a wrong folder is uploaded, or a release breaks the site and nobody remembers what the previous version looked like. This project builds deploy.sh, a script that deploys a directory in the way most professional teams do: every deployment becomes a new release directory, a symbolic link called current is switched to it in one atomic step, a health check decides whether the release is acceptable, and a failed release is undone automatically. Old releases are kept so that a rollback takes one command.
Earlier lessons covered the parts: lesson 177 (Bash in CI/CD), lesson 178 (configuration for deployment), lesson 179 (SSH tasks), lesson 180 (deploying a web application) and lesson 171 (lock files). This project combines them into one tool that is safe to run repeatedly.
What the Script Should Do
- Deploy a source directory to a target directory as a new, time-stamped release.
- Switch the
currentlink to the new release atomically, so visitors never see a half-copied site. - Check the new release with a command you provide, and restore the previous release automatically if the check fails.
- Keep only the newest few releases and delete the rest.
- Roll back to the previous release on request, and list the releases.
- Refuse to run twice at the same time, and offer a dry run that changes nothing.
The Release Layout
The script manages one target directory with this structure:
site/
├── current -> releases/20261202-203634 (symbolic link)
├── releases/
│ ├── 20261202-203630/
│ ├── 20261202-203631/
│ └── 20261202-203634/
└── .deploy.lock
A web server, application server or cron job always uses the path site/current. It never needs to know which release is active, because deploying and rolling back only change where the link points. The release names are timestamps in the form YYYYMMDD-HHMMSS. This is a deliberate choice: alphabetical order is also chronological order, so a plain sort is enough to find the oldest, the newest and the previous release.
Design Decisions
Copy First, Publish Second
A copy of a large directory takes time. If the script copied straight into releases/20261202-203634/, that name would exist while the copy is still running, and a crash would leave a broken release that looks complete. The script copies to a temporary name and renames it only when the copy has finished:
cp -a -- "$source" "$release.partial"
mv -- "$release.partial" "$release"
cp -a copies recursively and preserves permissions, timestamps and symbolic links. A rename inside one file system is a single, instant operation, so the release appears completely or not at all. The helper that lists releases skips names that end in .partial, so an interrupted copy is never mistaken for a release.
Switching the Link Atomically
The obvious way to change a link is ln -sfn new current, but that command removes the old link and creates the new one in two steps, and for a very short moment current does not exist. The script uses a two-step approach where the dangerous moment never happens:
switch_to() {
ln -sfn "releases/$1" "$target/.current.new"
mv -T "$target/.current.new" "$target/current"
}
It builds the new link under a temporary name and then renames it over the old one. mv -T treats the destination as a file and not as a directory (without it, mv would move the link into the directory that current points to). A rename that replaces an existing name is atomic on Linux, so a program that opens site/current/index.html sees either the old release or the new release, and never an error. The link target is relative (releases/NAME), so the whole site directory can be moved or copied to another machine without breaking the link.
Finding the Current Release
readlink prints where a link points, and a parameter expansion keeps the last part:
current_release() {
local link
link=$(readlink "$target/current" 2>/dev/null) || return 1
printf '%s\n' "${link##*/}"
}
${link##*/} removes the longest prefix that ends in /, which turns releases/20261202-203634 into 20261202-203634. When there is no link yet (the first deployment), readlink fails and the function returns 1, which the callers handle with || true.
Undoing a Failed Deployment
The health check is any command given with -c. It runs after the switch, because that is the only way to test the release in its real place with the real paths. If the command fails, the script switches the link back to the previous release and deletes the failed one:
if ! run_check; then
log "health check FAILED"
if [[ -n $previous ]]; then
switch_to "$previous"
else
rm -f -- "$target/current"
fi
rm -rf -- "${release:?}"
exit 1
fi
The check is started with bash -c "$check" "$target/current", so inside the check command $0 is the path of the current release. A check can therefore be a file test (test -f "$0/ready.txt"), a script of your own, or a request to the running application (curl -fsS http://localhost:8080/health). The expression ${release:?} stops the script with an error if the variable is ever empty, so a mistake can never turn the rm -rf into rm -rf "" or something worse.
Pruning Old Releases
Releases take disk space, so after a successful deployment the script keeps the newest KEEP of them (default 3). The release that current points to is never deleted, even if it is old. This matters after a rollback, when the active release is not the newest one:
prune() {
local cur all=() r
cur=$(current_release)
mapfile -t all < <(releases)
local excess=$(( ${#all[@]} - keep ))
for r in "${all[@]}"; do
(( excess > 0 )) || break
[[ $r == "$cur" ]] && continue
rm -rf -- "${target:?}/releases/${r:?}"
excess=$((excess - 1))
done
}
mapfile -t all reads the sorted release names into an array. The loop walks from the oldest, skips the active release and deletes until only KEEP remain.
One Deployment at a Time
Two deployments that run together would fight over the link and the release list. The script takes an exclusive lock with flock on file descriptor 9 (lesson 171):
exec 9> "${lockfile:-$target/.deploy.lock}"
flock -n 9 || { printf '%s: another deploy is running\n' "$PROG" >&2; exit 3; }
-n makes flock fail immediately instead of waiting. The lock belongs to the open descriptor, so the operating system releases it automatically when the script ends, even after a crash. No stale lock file can ever block future deployments.
The Complete Script
#!/usr/bin/env bash
#
# deploy.sh - deploy a directory as a new release and switch "current" to it
#
# Usage: deploy.sh [-n] [-k KEEP] [-c CHECK] [-l LOCKFILE] deploy SOURCE_DIR TARGET_DIR
# deploy.sh [-n] [-c CHECK] rollback TARGET_DIR
# deploy.sh list TARGET_DIR
#
# Options:
# -n dry run: show what would happen, change nothing
# -k KEEP releases to keep after a deploy (default: 3)
# -c CHECK command that must succeed after the switch (a health check);
# if it fails, the previous release is restored
# -l FILE lock file (default: TARGET_DIR/.deploy.lock)
# -h show this help
#
# TARGET_DIR layout: releases/<timestamp>/ one directory per release
# current -> releases/<timestamp> symbolic link
#
# Exit status: 0 success, 1 deploy failed (and was undone), 2 usage error, 3 locked.
set -euo pipefail
export LC_ALL=C
readonly PROG=${0##*/}
usage() { sed -n '3,22s/^# \{0,1\}//p' "$0"; }
die() { printf '%s: %s\n' "$PROG" "$1" >&2; exit 2; }
log() { printf '%s %s\n' "$(date '+%H:%M:%S')" "$*"; }
dry=0 keep=3 check= lockfile=
while getopts ':nk:c:l:h' opt; do
case $opt in
n) dry=1 ;;
k) keep=$OPTARG ;;
c) check=$OPTARG ;;
l) lockfile=$OPTARG ;;
h) usage; exit 0 ;;
:) die "option -$OPTARG needs a value" ;;
*) die "unknown option -$OPTARG (try -h)" ;;
esac
done
shift $((OPTIND - 1))
[[ $keep =~ ^[1-9][0-9]*$ ]] || die "-k needs a whole number of at least 1"
(( $# >= 1 )) || die "give a command: deploy, rollback or list (try -h)"
cmd=$1; shift
# --- helpers --------------------------------------------------------------------
# print the release names, oldest first (names are timestamps, so sorting is enough)
releases() {
local d
for d in "$target"/releases/*/; do
[[ -d $d ]] || continue
d=${d%/}
[[ $d == *.partial ]] && continue # a copy that was interrupted
printf '%s\n' "${d##*/}"
done | sort
}
current_release() {
local link
link=$(readlink "$target/current" 2>/dev/null) || return 1
printf '%s\n' "${link##*/}"
}
# replace the "current" link in one atomic step
switch_to() {
ln -sfn "releases/$1" "$target/.current.new"
mv -T "$target/.current.new" "$target/current"
}
run_check() {
[[ -z $check ]] && return 0
log "health check: $check"
bash -c "$check" "$target/current"
}
take_lock() {
exec 9> "${lockfile:-$target/.deploy.lock}"
flock -n 9 || { printf '%s: another deploy is running\n' "$PROG" >&2; exit 3; }
}
# --- commands -------------------------------------------------------------------
do_deploy() {
(( $# == 2 )) || die "deploy needs SOURCE_DIR and TARGET_DIR"
local source=$1; target=$2
[[ -d $source ]] || die "source is not a directory: $source"
[[ -n $(ls -A -- "$source") ]] || die "source directory is empty: $source"
local name; name=$(date '+%Y%m%d-%H%M%S')
local release=$target/releases/$name
local previous; previous=$(current_release || true)
if (( dry )); then
log "[dry run] would copy $source to $release"
log "[dry run] would switch current from '${previous:-none}' to '$name'"
log "[dry run] would keep the newest $keep release(s)"
return 0
fi
mkdir -p "$target/releases"
take_lock
[[ ! -e $release ]] || die "release $name already exists (wait one second)"
log "copying to $release"
cp -a -- "$source" "$release.partial" # never show a half-copied release
mv -- "$release.partial" "$release"
log "switching current: ${previous:-none} -> $name"
switch_to "$name"
if ! run_check; then
log "health check FAILED"
if [[ -n $previous ]]; then
log "restoring $previous"
switch_to "$previous"
else
log "no previous release; removing the failed link"
rm -f -- "$target/current"
fi
rm -rf -- "${release:?}"
exit 1
fi
prune
log "deployed $name"
}
prune() {
local cur all=() r
cur=$(current_release)
mapfile -t all < <(releases)
local excess=$(( ${#all[@]} - keep ))
for r in "${all[@]}"; do
(( excess > 0 )) || break
[[ $r == "$cur" ]] && continue
log "removing old release $r"
rm -rf -- "${target:?}/releases/${r:?}"
excess=$((excess - 1))
done
}
do_rollback() {
(( $# == 1 )) || die "rollback needs TARGET_DIR"
target=$1
[[ -d $target/releases ]] || die "no releases in $target"
local cur prev="" r
cur=$(current_release) || die "there is no current release"
while read -r r; do
[[ $r == "$cur" ]] && break
prev=$r
done < <(releases)
[[ -n $prev ]] || die "no older release to go back to"
if (( dry )); then
log "[dry run] would switch current from $cur to $prev"
return 0
fi
take_lock
log "rolling back: $cur -> $prev"
switch_to "$prev"
run_check || { log "health check failed after rollback"; exit 1; }
}
do_list() {
(( $# == 1 )) || die "list needs TARGET_DIR"
target=$1
local cur r
cur=$(current_release || true)
while read -r r; do
if [[ $r == "$cur" ]]; then printf '* %s\n' "$r"; else printf ' %s\n' "$r"; fi
done < <(releases)
}
target=
case $cmd in
deploy) do_deploy "$@" ;;
rollback) do_rollback "$@" ;;
list) do_list "$@" ;;
*) die "unknown command '$cmd' (try -h)" ;;
esac
Running a Deployment
The examples use a small application directory:
mkdir -p app/static
echo "v1" > app/version.txt
echo '<h1>hello</h1>' > app/static/index.html
Dry Run
$ ./deploy.sh -n deploy app site
20:36:28 [dry run] would copy app to site/releases/20261202-203628
20:36:28 [dry run] would switch current from 'none' to '20261202-203628'
20:36:28 [dry run] would keep the newest 3 release(s)
Nothing was created: the directory site does not exist after the dry run. Use -n first whenever you deploy somewhere new.
The First Deployment
$ ./deploy.sh deploy app site
20:36:28 copying to site/releases/20261202-203628
20:36:28 switching current: none -> 20261202-203628
20:36:28 deployed 20261202-203628
Several Deployments and Pruning
After changing version.txt and deploying three more times (with -k 3 as the default), the oldest release is removed during the fourth deployment:
$ ./deploy.sh deploy app site
20:36:31 copying to site/releases/20261202-203631
20:36:31 switching current: 20261202-203630 -> 20261202-203631
20:36:31 removing old release 20261202-203628
20:36:31 deployed 20261202-203631
$ ./deploy.sh list site
20261202-203629
20261202-203630
* 20261202-203631
$ cat site/current/version.txt
v4
The list command marks the active release with an asterisk.
Rolling Back
$ ./deploy.sh rollback site
20:36:32 rolling back: 20261202-203631 -> 20261202-203630
$ ./deploy.sh list site
20261202-203629
* 20261202-203630
20261202-203631
$ cat site/current/version.txt
v3
The faulty release 203631 still exists, which is useful for finding out what went wrong. The rollback finds the release before the active one by reading the sorted list until it reaches the active name, and it remembers the previous name on the way.
A Failing Health Check
The check below requires a file ready.txt in the release. The new version does not contain it, so the check fails and the script puts everything back:
$ ./deploy.sh -c 'test -f "$0/ready.txt"' deploy app site
20:36:33 copying to site/releases/20261202-203633
20:36:33 switching current: 20261202-203630 -> 20261202-203633
20:36:33 health check: test -f "$0/ready.txt"
20:36:33 health check FAILED
20:36:33 restoring 20261202-203630
$ echo $?
1
$ ./deploy.sh list site
20261202-203629
* 20261202-203630
20261202-203631
The failed release 203633 is gone, current points to the old release again, and the exit status is 1, so a CI job that runs the script fails as it should. After adding the file (touch app/ready.txt), the same command succeeds and prints deployed ....
Two Deployments at the Same Time
While another process holds the lock, the script refuses to start:
$ ./deploy.sh deploy app site
deploy.sh: another deploy is running
$ echo $?
3
Input Errors
All of the following exit with status 2:
$ ./deploy.sh
deploy.sh: give a command: deploy, rollback or list (try -h)
$ ./deploy.sh deploy nodir site
deploy.sh: source is not a directory: nodir
$ ./deploy.sh deploy empty site
deploy.sh: source directory is empty: empty
$ ./deploy.sh -k 0 list site
deploy.sh: -k needs a whole number of at least 1
$ ./deploy.sh bogus x
deploy.sh: unknown command 'bogus' (try -h)
$ ./deploy.sh rollback fresh
deploy.sh: no releases in fresh
Refusing an empty source directory protects against a very common accident: a build step that fails silently produces an empty folder, and deploying it would replace a working site with nothing.
Deploying to a Remote Server
The script works on one machine. To deploy to a server, copy the source there first and run the script on the server. With the tools from lesson 179, the whole procedure is three commands:
tar -C app -czf - . | ssh deploy@server 'mkdir -p /tmp/app-new && tar -C /tmp/app-new -xzf -'
ssh deploy@server '/usr/local/bin/deploy.sh -c "curl -fsS http://localhost:8080/health" deploy /tmp/app-new /srv/site'
ssh deploy@server 'rm -rf /tmp/app-new'
The first command packs the directory into a compressed stream and unpacks it on the server without creating an archive file. The second runs the deployment there with a real health check. Run these steps from a CI job (lesson 177), and the exit status of the script decides whether the pipeline passes.
Ideas for Extending the Project
- Shared data. Keep uploads and logs in
site/shared/and link them into every release, so that they survive deployments. - Hooks. Run
before-switchandafter-switchscripts from the release (for example to run database migrations or restart a service). - Retry the check. Many applications need a few seconds to start; retry the health check up to ten times with
sleep 1between the attempts. - Notifications. Call the notification script from lesson 173 when a deployment succeeds, fails or rolls back.
- Checksums. Store
sha256sumof the source in the release, and verify it after copying to a server.