Build a Deployment Automation Script

Su Suriya Ravichandran Updated 06 Dec 2026
13 min read ·Lesson 203 of 205

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

  1. Deploy a source directory to a target directory as a new, time-stamped release.
  2. Switch the current link to the new release atomically, so visitors never see a half-copied site.
  3. Check the new release with a command you provide, and restore the previous release automatically if the check fails.
  4. Keep only the newest few releases and delete the rest.
  5. Roll back to the previous release on request, and list the releases.
  6. 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.

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-switch and after-switch scripts 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 1 between the attempts.
  • Notifications. Call the notification script from lesson 173 when a deployment succeeds, fails or rolls back.
  • Checksums. Store sha256sum of the source in the release, and verify it after copying to a server.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Build a Deployment Automation Script and get answers drawn from it.

Signed-in readers only.