Building Repeatable Development Setup Scripts

Su Suriya Ravichandran Updated 06 Dec 2026
24 min read ·Lesson 182 of 205

A development setup script prepares a computer to work on a project: it checks that the right tools are installed, creates local configuration files, installs the project's libraries, and configures things like Git hooks. Instead of a README with fifteen manual steps that every new team member follows slightly differently, the project contains one command, for example scripts/setup-dev.sh, that brings any machine into the same working state.

The word that matters is repeatable. A good setup script is not only run once on a new laptop. It is run again after pulling changes that add a dependency, after upgrading the operating system, or whenever something behaves strangely. Every run must be safe, must leave alone what is already correct, and must repair what is missing or outdated. This lesson explains the technique that makes this possible, idempotency, and builds a complete setup script for a project with Python and Node.js parts.

Idempotency: Check, Act, Verify

An operation is idempotent when performing it once or many times gives the same result. mkdir -p var/log is idempotent: the first run creates the directory, and later runs succeed without changing anything. echo 'export PATH=...' >> ~/.bashrc is not: every run appends another copy of the line.

A setup script is idempotent when each of its steps follows the same pattern:

  1. Check whether the desired state already exists, for example "the virtual environment exists and works".
  2. Act only if it does not, for example "create the virtual environment".
  3. Verify after acting that the check now passes, because a command that exits with status 0 has not necessarily produced the desired result.

The append example shows the difference. The idempotent version checks for the exact line first:

line='export PATH="$HOME/.local/bin:$PATH"'
grep -qxF -- "$line" ~/.bashrc || echo "$line" >> ~/.bashrc

grep -q searches silently and reports the result only through its exit status. -x requires the whole line to match, and -F treats the pattern as fixed text, so the $ and . characters in it are not interpreted as regular expression syntax. The echo runs only when the line is not already there.

Thinking in desired states rather than in commands has a second benefit: each step can report what it found. A run that prints "ok" for ten steps and "changed" for one tells the developer exactly what was repaired, and the same check function can power a dry-run mode that shows what would change without changing anything.

A Reusable ensure Function

Because every step follows the same pattern, the pattern can be written once as a function that receives the check and the action as function names:

# ensure DESCRIPTION CHECK ACTION [ARGS...]
# Runs CHECK ARGS. If it fails, runs ACTION ARGS and then CHECK again to verify.
ensure() {
    local desc=$1 check=$2 action=$3 log
    shift 3
    if "$check" "$@"; then report ok "$desc"; return 0; fi
    if (( DRY_RUN )); then report would "$desc"; return 0; fi
    log=$(mktemp)
    if "$action" "$@" > "$log" 2>&1 && "$check" "$@"; then
        report changed "$desc"
    else
        report failed "$desc"
        tail -n 4 "$log" | sed 's/^/           | /'
    fi
    rm -f -- "$log"
}

The first three parameters are a description and two function names; shift 3 removes them, so "$@" holds the remaining arguments, which are passed to both functions. Bash runs "$check" "$@" as a command, so the variable's value, the name of a function, is called. The check's exit status decides what happens:

  • If it succeeds, the step is reported as ok and nothing runs.
  • In a dry run, the step is reported as would and nothing runs.
  • Otherwise the action runs with its output captured in a temporary file. If the action succeeds and the check now passes, the step is changed. If either fails, the step is FAILED and the last four lines of the captured output are shown, indented under the step, so the developer sees the reason without wading through pages of installer output.

A failed step does not stop the script. A setup script that stops at the first problem forces developers into a slow loop of "fix one thing, run again, find the next thing". Reporting every problem in one run, and exiting with a non-zero status at the end, is more useful.

With this function, each step of the setup becomes a pair of small functions and one line:

DIRS=(var/log var/uploads)
dirs_ok()  { local d; for d in "${DIRS[@]}"; do [[ -d $d ]] || return 1; done; }
dirs_fix() { mkdir -p "${DIRS[@]}"; }

ensure 'var/log and var/uploads exist' dirs_ok dirs_fix

Why Actions Must Chain Their Commands

There is one important rule for action functions. ensure calls them as the condition of an if, and in a condition, set -e has no effect, not even inside the functions it calls (lesson 119). A failing command in the middle of an action does not stop the action:

#!/usr/bin/env bash
set -e
action() {
    false                      # fails...
    echo "still running"       # ...but set -e does not stop the function
}
if action; then echo "action reported success"; fi
action
echo "not reached"
still running
action reported success
[status 1]

Inside the if, the failure of false was ignored, echo ran, and because echo succeeded, the whole function reported success. Called outside a condition, the same function stopped the script immediately. Action functions in a setup script therefore connect their commands with &&, so that the first failure ends the function with a failing status:

venv_fix() { rm -rf .venv && python3 -m venv .venv; }

The verification step in ensure is a second safety net: even if an action misreports success, the check that runs after it catches the problem.

Checking Tools and Versions

Most projects need certain programs in certain minimum versions. Checking that a command exists is done with command -v, which is built into Bash and prints the command's location if it is found:

have() { command -v "$1" > /dev/null 2>&1; }

which is often used for this, but it is an external program whose behavior differs between systems; command -v is part of the POSIX standard and also finds functions, aliases and built-ins.

Comparing versions is harder than it looks, because version numbers are not decimals and not plain strings. A string comparison gets it wrong as soon as a component has two digits:

[[ "3.9.2" > "3.11" ]] && echo "string comparison says 3.9.2 is newer"
string comparison says 3.9.2 is newer

Strings are compared character by character, and 9 sorts after 1. Correct comparison splits the version at the dots and compares each component as a number:

version_ge() {                                   # version_ge HAVE NEED
    local IFS=. i
    local -a h=($1) n=($2)
    for (( i = 0; i < ${#n[@]}; i++ )); do
        (( 10#${h[i]:-0} > 10#${n[i]} )) && return 0
        (( 10#${h[i]:-0} < 10#${n[i]} )) && return 1
    done
    return 0
}

Setting IFS to . inside the function makes the unquoted $1 split at dots, so h=($1) turns 3.13.18 into the array (3 13 18). The loop compares component by component and returns as soon as one differs. ${h[i]:-0} treats a missing component as 0, so 3.11 and 3.11.0 are equal. The 10# prefix forces base 10; without it, Bash would read a component such as 08 as an invalid octal number. If all components are equal, the installed version is new enough. A few tests confirm the behavior:

3.13.18 >= 3.11: yes
3.9.2 >= 3.11: no
22.11.0 >= 20: yes
1.10 >= 1.9: yes
1.6 >= 1.6: yes
0.8.0 >= 0.9: no

On Linux, sort -V (version sort) from GNU coreutils can also order version strings, but the hand-written function works the same everywhere.

Every program reports its version differently, so a small function extracts a plain version number for each tool:

tool_version() {
    case $1 in
        git)        git --version | awk '{ print $3 }' ;;            # git version 2.43.0
        python3)    python3 -c 'import sys; print("%d.%d.%d" % sys.version_info[:3])' ;;
        node)       node --version | tr -d v ;;                       # v22.11.0
        jq)         jq --version | sed 's/^jq-//' ;;                  # jq-1.7.1
        shellcheck) shellcheck --version | awk '/^version:/ { print $2 }' ;;
    esac
}

For Python, asking the interpreter for sys.version_info is more reliable than parsing python3 --version, whose output format has changed between releases.

Installing Missing Tools

When a tool is missing or too old, the script can install it with the system's package manager. Package managers differ between platforms, so the script detects which one is available:

if   have apt-get; then PM=apt         # Debian, Ubuntu
elif have dnf;     then PM=dnf         # Fedora, RHEL
elif have brew;    then PM=brew        # macOS with Homebrew
else                    PM=none
fi

Package names also differ: Node.js is the program node but the package nodejs on Debian and Fedora. A case statement on the combination of package manager and tool handles these exceptions.

Installing system packages needs administrator rights, and it changes the developer's computer outside the project directory. Some developers do not want a project script to do that, or they install tools in their own way, through version managers such as pyenv or nvm. A good setup script therefore offers an option to only report missing tools. In the complete example below, --no-install does this.

Two details are easy to miss. First, sudo is needed only when the script is not already running as root; inside a Docker container, the user is usually root and sudo may not even be installed. Second, apt-get install fails with "Unable to locate package" on systems whose package lists were never downloaded, which is the normal state of a fresh container image. The script runs apt-get update once, before the first installation.

Configuration Files: Create, Never Overwrite

Most projects need a local configuration file with settings such as database addresses and secret keys. The usual convention (lesson 178) is a template, .env.example, committed to the repository, and a real .env, created from it, which is listed in .gitignore because each developer's values are different and may contain secrets.

The setup script must create .env when it is missing but must never overwrite an existing one: it contains the developer's own values. There is a subtler case too. When a teammate adds a new setting to .env.example, existing .env files lack it, and the application fails with a confusing error. The script detects missing keys and appends them with their example values, leaving every existing line untouched:

env_keys() { sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p' "$1" | sort; }
env_missing() {                                  # keys in .env.example that .env lacks
    if [[ -f .env ]]; then comm -23 <(env_keys .env.example) <(env_keys .env)
    else env_keys .env.example; fi
}
env_ok() { [[ -f .env && -z $(env_missing) ]]; }

env_keys prints the sorted names of all settings in a file: the sed expression matches lines of the form NAME=value, captures the name, and prints only that (-n suppresses all other output). comm compares two sorted lists and prints three columns: lines only in the first, lines only in the second, and lines in both. -23 hides the second and third columns, leaving the keys that exist in the template but not in .env. The two <( ) constructs are process substitutions (lesson 151), which let comm read the output of commands as if they were files.

Dependencies: Reinstall Only When Something Changed

Installing a project's libraries, with pip install -r requirements.txt for Python or npm ci for Node.js, takes from seconds to minutes. Running it on every setup run would make the script slow, and developers would stop running it. Skipping it when the libraries are already installed is wrong too, because the dependency list may have changed since then.

The solution is a stamp file: after a successful installation, the script stores a checksum of the dependency file. On the next run, it compares the stored checksum with the current one. If they match, the dependencies are up to date; if the dependency file was changed, for example by a git pull, the checksums differ and the installation runs again:

hash_of() {                                      # SHA-256 of a file, Linux or macOS
    if have sha256sum; then sha256sum < "$1"; else shasum -a 256 < "$1"; fi
}

pydeps_ok() {
    [[ -f .venv/.requirements.sha256 ]] &&
        [[ $(hash_of requirements.txt) == "$(< .venv/.requirements.sha256)" ]]
}
pydeps_fix() {
    .venv/bin/pip install --quiet --disable-pip-version-check -r requirements.txt &&
        hash_of requirements.txt > .venv/.requirements.sha256
}

The stamp is written only after a successful installation, because of the &&. An interrupted or failed installation leaves no stamp, so the next run tries again. The stamp is stored inside the directory it describes, .venv: if the virtual environment is deleted or rebuilt, the stamp disappears with it, and the packages are reinstalled automatically. $(< file) reads a file's content without starting cat.

Linux has sha256sum, and macOS has shasum -a 256 instead; hash_of uses whichever exists. Reading the file through < makes both commands print only the checksum followed by -, so their output is identical in format.

Git Settings

Projects often provide Git hooks, small scripts that Git runs automatically, for example before each commit. Hooks live in .git/hooks, which is not part of the repository, so they cannot be shared directly. Since Git 2.9, the core.hooksPath setting tells Git to take hooks from another directory, which can be a directory in the repository. The setup script turns it on:

hooks_ok()  { [[ $(git config --get core.hooksPath || true) == scripts/hooks ]]; }
hooks_fix() { git config core.hooksPath scripts/hooks; }

git config --get exits with status 1 when the setting does not exist; || true keeps that from aborting the script under set -e and pipefail and simply compares an empty string.

A Complete Example: setup-dev.sh

The demo project "shop" has a Python back end with requirements.txt, a Node.js front end with package.json and package-lock.json, a .env.example template, and a pre-commit hook in scripts/hooks that checks shell scripts with ShellCheck (lesson 162). Its setup script combines all the techniques from this lesson:

#!/usr/bin/env bash
#
# setup-dev.sh - prepare or repair the development environment of the shop project
#
# Usage: scripts/setup-dev.sh [--dry-run] [--no-install]
#   --dry-run      show what would change, change nothing
#   --no-install   never install system packages, only report missing tools
#
# Safe to run any number of times: every step checks first and acts only when needed.
# Written for Bash 3.2 or later, so it also runs with the Bash that macOS ships.

set -euo pipefail

cd "$(dirname "${BASH_SOURCE[0]}")/.."          # always work in the project root

DRY_RUN=0 INSTALL=1
for arg in "$@"; do
    case $arg in
        --dry-run)    DRY_RUN=1 ;;
        --no-install) INSTALL=0 ;;
        -h|--help)    sed -n '5,7s/^# \{0,1\}//p' "$0"; exit 0 ;;
        *)            echo "${0##*/}: unknown option: $arg" >&2; exit 2 ;;
    esac
done

# ---------------------------------------------------------------- reporting
ok=0 changed=0 failed=0
if [[ -t 1 ]]; then G=$'\e[32m' Y=$'\e[33m' R=$'\e[31m' B=$'\e[1m' N=$'\e[0m'
else G='' Y='' R='' B='' N=''; fi

heading() { printf '%s%s%s\n' "$B" "$1" "$N"; }
report() {                                       # report STATE DESCRIPTION
    case $1 in
        ok)      printf '  %sok%s       %s\n' "$G" "$N" "$2"; ok=$(( ok + 1 )) ;;
        changed) printf '  %schanged%s  %s\n' "$Y" "$N" "$2"; changed=$(( changed + 1 )) ;;
        would)   printf '  %swould%s    %s\n' "$Y" "$N" "$2"; changed=$(( changed + 1 )) ;;
        failed)  printf '  %sFAILED%s   %s\n' "$R" "$N" "$2"; failed=$(( failed + 1 )) ;;
    esac
}

# ensure DESCRIPTION CHECK ACTION [ARGS...]
# Runs CHECK ARGS. If it fails, runs ACTION ARGS and then CHECK again to verify.
ensure() {
    local desc=$1 check=$2 action=$3 log
    shift 3
    if "$check" "$@"; then report ok "$desc"; return 0; fi
    if (( DRY_RUN )); then report would "$desc"; return 0; fi
    log=$(mktemp)
    if "$action" "$@" > "$log" 2>&1 && "$check" "$@"; then
        report changed "$desc"
    else
        report failed "$desc"
        tail -n 4 "$log" | sed 's/^/           | /'
    fi
    rm -f -- "$log"
}

# ---------------------------------------------------------------- helpers
have() { command -v "$1" > /dev/null 2>&1; }

version_ge() {                                   # version_ge HAVE NEED
    local IFS=. i
    local -a h=($1) n=($2)
    for (( i = 0; i < ${#n[@]}; i++ )); do
        (( 10#${h[i]:-0} > 10#${n[i]} )) && return 0
        (( 10#${h[i]:-0} < 10#${n[i]} )) && return 1
    done
    return 0
}

hash_of() {                                      # SHA-256 of a file, Linux or macOS
    if have sha256sum; then sha256sum < "$1"; else shasum -a 256 < "$1"; fi
}

SUDO='' apt_updated=0
(( EUID == 0 )) || SUDO=sudo
if   have apt-get; then PM=apt
elif have dnf;     then PM=dnf
elif have brew;    then PM=brew
else                    PM=none
fi

# ---------------------------------------------------------------- system tools
tool_version() {
    case $1 in
        git)        git --version | awk '{ print $3 }' ;;
        python3)    python3 -c 'import sys; print("%d.%d.%d" % sys.version_info[:3])' ;;
        node)       node --version | tr -d v ;;
        jq)         jq --version | sed 's/^jq-//' ;;
        shellcheck) shellcheck --version | awk '/^version:/ { print $2 }' ;;
    esac
}

tool_ok() {                                      # tool_ok TOOL MIN_VERSION
    have "$1" && version_ge "$(tool_version "$1")" "$2"
}

install_tool() {                                 # install_tool TOOL MIN_VERSION
    local pkg=$1
    case $PM:$1 in
        apt:node|dnf:node) pkg=nodejs ;;
    esac
    if (( ! INSTALL )); then
        echo "$1 $2 or later is required; install it, then run this script again"
        return 1
    fi
    case $PM in
        apt)  if (( ! apt_updated )); then        # refresh package lists once per run
                  $SUDO apt-get update && apt_updated=1
              fi
              $SUDO apt-get install -y "$pkg" ;;
        dnf)  $SUDO dnf install -y "$pkg" ;;
        brew) brew install "$pkg" ;;
        *)    echo "no supported package manager found; install $1 manually"; return 1 ;;
    esac
}

# ---------------------------------------------------------------- project files
env_keys() { sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p' "$1" | sort; }
env_missing() {                                  # keys in .env.example that .env lacks
    if [[ -f .env ]]; then comm -23 <(env_keys .env.example) <(env_keys .env)
    else env_keys .env.example; fi
}
env_ok() { [[ -f .env && -z $(env_missing) ]]; }
env_fix() {
    local key
    if [[ ! -f .env ]]; then
        cp .env.example .env && chmod 600 .env
        return
    fi
    {
        printf '\n# added by setup-dev.sh on %s, copied from .env.example\n' "$(date +%F)"
        for key in $(env_missing); do
            grep "^$key=" .env.example
        done
    } >> .env
}

DIRS=(var/log var/uploads)
dirs_ok()  { local d; for d in "${DIRS[@]}"; do [[ -d $d ]] || return 1; done; }
dirs_fix() { mkdir -p "${DIRS[@]}"; }

# ---------------------------------------------------------------- dependencies
venv_ok()  { [[ -x .venv/bin/python ]] && .venv/bin/python -c 'import sys' 2> /dev/null; }
venv_fix() { rm -rf .venv && python3 -m venv .venv; }

pydeps_ok() {
    [[ -f .venv/.requirements.sha256 ]] &&
        [[ $(hash_of requirements.txt) == "$(< .venv/.requirements.sha256)" ]]
}
pydeps_fix() {
    .venv/bin/pip install --quiet --disable-pip-version-check -r requirements.txt &&
        hash_of requirements.txt > .venv/.requirements.sha256
}

nodedeps_ok() {
    [[ -f node_modules/.lock.sha256 ]] &&
        [[ $(hash_of package-lock.json) == "$(< node_modules/.lock.sha256)" ]]
}
nodedeps_fix() {
    npm ci --no-audit --no-fund &&
        mkdir -p node_modules &&        # npm creates no node_modules when nothing is installed
        hash_of package-lock.json > node_modules/.lock.sha256
}

# ---------------------------------------------------------------- git
hooks_ok()  { [[ $(git config --get core.hooksPath || true) == scripts/hooks ]]; }
hooks_fix() { git config core.hooksPath scripts/hooks; }

# ---------------------------------------------------------------- run
(( DRY_RUN )) && echo "Dry run: nothing will be changed."

heading 'System tools'
ensure 'git 2.30 or later'        tool_ok install_tool git 2.30
ensure 'python3 3.11 or later'    tool_ok install_tool python3 3.11
ensure 'node 20 or later'         tool_ok install_tool node 20
ensure 'jq 1.6 or later'          tool_ok install_tool jq 1.6
ensure 'shellcheck 0.9 or later'  tool_ok install_tool shellcheck 0.9

heading 'Project files'
ensure '.env has every setting from .env.example' env_ok   env_fix
ensure 'var/log and var/uploads exist'            dirs_ok  dirs_fix

heading 'Dependencies'
ensure 'Python virtual environment in .venv'      venv_ok     venv_fix
ensure 'Python packages match requirements.txt'   pydeps_ok   pydeps_fix
ensure 'node_modules matches package-lock.json'   nodedeps_ok nodedeps_fix

heading 'Git'
ensure 'Git hooks from scripts/hooks are active'  hooks_ok hooks_fix

if (( DRY_RUN )); then
    printf '\n%d ok, %d would change, %d failed\n' "$ok" "$changed" "$failed"
else
    printf '\n%d ok, %d changed, %d failed\n' "$ok" "$changed" "$failed"
fi
exit $(( failed > 0 ))

How It Works

  • Working directory. cd "$(dirname "${BASH_SOURCE[0]}")/.." moves to the project root, the parent of the script's own directory. All later paths, such as .env and .venv, are relative to it, so the script works no matter from where it is started.
  • Options. The project has only two flags, so a simple loop over the arguments is enough instead of getopts (lesson 130). Unknown options stop the script with status 2.
  • Colors only on a terminal. [[ -t 1 ]] tests whether standard output is a terminal. Color codes help a person read the result but would put escape characters into a log file or CI output, so they are turned off otherwise.
  • Counting results. report prints each result and counts it. The counters are increased with x=$(( x + 1 )) rather than (( x++ )), because (( x++ )) returns a failing status when the old value is 0, which would stop a script running with set -e (lesson 119).
  • The step list. The end of the script reads like a checklist: one ensure line per desired state, grouped under headings. Adding a requirement to the project means adding one line and, if needed, a check and an action function.
  • The final status. exit $(( failed > 0 )) exits with 1 if any step failed and 0 otherwise, so a CI pipeline or another script can rely on the result (lesson 177).
  • Portability. macOS still ships Bash 3.2 as /bin/bash, and many developers do not install a newer one. The script avoids features added in later versions, such as associative arrays, mapfile, the ${var,,} case conversion and printf '%(...)T'. The tests below were run with Bash 5.2 on Ubuntu 24.04.

Running the Complete Example

The demo project was created as a fresh Git repository. Its requirements.txt installs a small helper package from a wheel file stored in the repository, so the tests ran without internet access; a real project would list packages from the Python Package Index.

A dry run on a fresh clone shows what the script would do, without changing anything:

$ scripts/setup-dev.sh --dry-run
Dry run: nothing will be changed.
System tools
  ok       git 2.30 or later
  ok       python3 3.11 or later
  ok       node 20 or later
  ok       jq 1.6 or later
  would    shellcheck 0.9 or later
Project files
  would    .env has every setting from .env.example
  would    var/log and var/uploads exist
Dependencies
  would    Python virtual environment in .venv
  would    Python packages match requirements.txt
  would    node_modules matches package-lock.json
Git
  would    Git hooks from scripts/hooks are active

4 ok, 7 would change, 0 failed
[status 0]

The first real run with --no-install revealed a bug in the first version of the script:

$ scripts/setup-dev.sh --no-install
System tools
  ok       git 2.30 or later
  ok       python3 3.11 or later
  ok       node 20 or later
  ok       jq 1.6 or later
  FAILED   shellcheck 0.9 or later
           | shellcheck 0.9 or later is required; install it, then run this script again
Project files
  changed  .env has every setting from .env.example
  changed  var/log and var/uploads exist
Dependencies
  changed  Python virtual environment in .venv
  changed  Python packages match requirements.txt
  FAILED   node_modules matches package-lock.json
           |
           | up to date in 155ms
           | scripts/setup-dev.sh: line 159: node_modules/.lock.sha256: No such file or directory
Git
  changed  Git hooks from scripts/hooks are active

4 ok, 5 changed, 2 failed
[status 1]

The ShellCheck failure is expected: the tool is not installed, and --no-install forbids installing it. The second failure was not expected. The demo front end has no dependencies yet, and in that case npm ci succeeds without creating a node_modules directory, so writing the stamp file into it failed. The captured output under the step made the cause obvious. The version shown above adds mkdir -p node_modules before writing the stamp. The next run repaired the step, and the run after that found nothing to do except the missing tool:

$ scripts/setup-dev.sh --no-install
...
Dependencies
  ok       Python virtual environment in .venv
  ok       Python packages match requirements.txt
  changed  node_modules matches package-lock.json
...
9 ok, 1 changed, 1 failed
[status 1]
$ scripts/setup-dev.sh --no-install
...
10 ok, 0 changed, 1 failed
[status 1]

The created environment works, and .env was created from the template with permissions that only allow the owner to read it:

$ ls -l .env
-rw------- 1 root root 169 Dec  1 05:50 .env
$ .venv/bin/python -c 'import shoputils; print(shoputils.price(1999))'
19.99 EUR
$ git config core.hooksPath
scripts/hooks

Without --no-install, the script tries to install ShellCheck. The test machine had no internet access, so apt-get could not download anything, which shows how a failed installation is reported:

$ scripts/setup-dev.sh
System tools
  ok       git 2.30 or later
  ok       python3 3.11 or later
  ok       node 20 or later
  ok       jq 1.6 or later
  FAILED   shellcheck 0.9 or later
           | Reading package lists...
           | Building dependency tree...
           | Reading state information...
           | E: Unable to locate package shellcheck
...

Repairing Drift

The real value of an idempotent script shows weeks later, when the environment has drifted from the project's requirements. To simulate this, four changes were made: the developer changed SECRET_KEY in .env to their own value; a teammate added REDIS_URL to .env.example; requirements.txt was edited; and the virtual environment was broken by deleting its python link, which is what happens to a virtual environment when the Python version it was created with is removed by a system upgrade. For the rest of the test, ShellCheck was replaced by a small stand-in program that reports version 0.10.0, since the real package could not be downloaded.

The dry run finds exactly the three things that need repair, and the real run repairs them:

$ scripts/setup-dev.sh --dry-run
Dry run: nothing will be changed.
System tools
  ok       git 2.30 or later
  ok       python3 3.11 or later
  ok       node 20 or later
  ok       jq 1.6 or later
  ok       shellcheck 0.9 or later
Project files
  would    .env has every setting from .env.example
  ok       var/log and var/uploads exist
Dependencies
  would    Python virtual environment in .venv
  would    Python packages match requirements.txt
  ok       node_modules matches package-lock.json
Git
  ok       Git hooks from scripts/hooks are active

8 ok, 3 would change, 0 failed
[status 0]
$ scripts/setup-dev.sh
...
Project files
  changed  .env has every setting from .env.example
  ok       var/log and var/uploads exist
Dependencies
  changed  Python virtual environment in .venv
  changed  Python packages match requirements.txt
  ok       node_modules matches package-lock.json
...
8 ok, 3 changed, 0 failed
[status 0]

The rebuilt virtual environment no longer contained the stamp file, so the packages were reinstalled as part of the repair. In .env, the developer's own SECRET_KEY survived, and the new setting was appended with a comment that explains where it came from:

$ cat .env
# Copy of the settings the shop needs; setup-dev.sh creates .env from this file
DATABASE_URL=postgresql://shop:shop@localhost:5432/shop_dev
SECRET_KEY=my-local-secret
DEBUG=1

# added by setup-dev.sh on 2026-12-01, copied from .env.example
REDIS_URL=redis://localhost:6379/0

One more run confirms that the environment is complete, and the script also works when started from another directory and rejects unknown options:

$ scripts/setup-dev.sh | tail -n 1
11 ok, 0 changed, 0 failed
$ cd /tmp && ~/shop/scripts/setup-dev.sh --bogus
setup-dev.sh: unknown option: --bogus
[status 2]

Keeping the Script Useful

A setup script is only trusted if it stays in step with the project. Teams that rely on one usually adopt a few habits:

  • Run it in CI. A CI job that runs the setup script in a clean container, such as ubuntu:24.04, proves on every change that a new machine can still be set up. Running it a second time in the same job and checking for 0 changed proves that it is idempotent.
  • Change it together with the project. When a pull request adds a dependency, a setting or a required tool, it updates .env.example, the dependency files or the script in the same change.
  • Keep project tools inside the project. Libraries belong in .venv and node_modules, not in global locations. The script then needs administrator rights only for a small number of system tools, and different projects on the same machine cannot conflict.
  • Know when to use something else. When the setup grows to include databases, message queues and several services, containers (lessons 175 and 176) or a dev container definition describe the environment more completely. A setup script then shrinks to checking that Docker is installed and starting the containers, and the same check-act-verify structure still applies.

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 Building Repeatable Development Setup Scripts and get answers drawn from it.

Signed-in readers only.