DEV Community

Cover image for How to Write Cross-Platform Shell Scripts: Stop Writing Bash That Only Runs on Your Machine
Mango Developer
Mango Developer

Posted on Originally published at mangodeveloper.com

How to Write Cross-Platform Shell Scripts: Stop Writing Bash That Only Runs on Your Machine

The first time I wrote an installer script and a coworker ran it on macOS, it failed on line 14. I'd used sed -i without a backup extension, which works on GNU sed and breaks on BSD sed. I'd used date +%s for a timestamp, which worked. I'd used readlink -f to resolve a path, which doesn't exist on macOS at all. The script worked on three Linux distros and broke on every Mac. I had no idea shell scripting was this fragmented.

This is the article I wish I'd had. We'll cover the baseline that runs everywhere, the BSD-vs-GNU differences that bite everyone, OS and architecture detection, package manager abstraction, the patterns that survive in real installers, and the tooling (shellcheck, shellspec) that catches the bugs before your users do. By the end, you'll have a script that runs on Debian, Ubuntu, Alpine, macOS, and FreeBSD without an apology in the README.

Why This Is Harder Than It Looks

The Unix shell ecosystem looks unified from the outside. It isn't. The fragments:

Fragment What it ships What it doesn't
Debian/Ubuntu bash 5, GNU coreutils, GNU sed, GNU find none
Alpine busybox ash, busybox applets bash (unless installed), GNU coreutils (unless installed)
macOS bash 3.2 (Catalina and later ship zsh), BSD userland GNU coreutils (without brew)
FreeBSD sh (dash-like), BSD userland bash (unless installed)
RHEL/Fedora bash 5, GNU coreutils none
NixOS bash 5, GNU coreutils paths in /run/current-system/sw/bin, not /usr/bin

And that's before you get to Git Bash on Windows, WSL, MSYS2, and the various Linux subsystems on ChromeOS. The POSIX shell standard exists, but the standard is the floor, not the ceiling-sed, find, awk, date, readlink, grep, xargs, tar all have BSD and GNU variants with subtly different flags.

If your script is going to run on more than one platform, you have two options: stick to the POSIX minimum, or detect the platform and branch. Real installers do both.

Prerequisites

  • A POSIX shell available locally: sh, dash, or bash --posix. macOS has sh. Debian has dash. Alpine has busybox ash.
  • A Linux box and a macOS box (or VMs) for testing. WSL on Windows is fine for Linux.
  • shellcheck installed. If you're not running shellcheck on every script, you're leaving bugs in.
  • shellspec for unit testing (optional but valuable for non-trivial scripts).
  • A text editor that doesn't add CRLF line endings. Yes, this matters.

The Shebang Question

BashCopy

Enter fullscreen mode Exit fullscreen mode

!/bin/sh # POSIX shell, portable everywhere, no bashisms

!/bin/bash # Bash, available on Linux/macOS, NOT on Alpine/FreeBSD by default

!/usr/bin/env bash # Bash via PATH lookup, works if bash is installed

!/usr/bin/env -S bash -euo pipefail # Bash with strict mode, requires env -S (coreutils 8.30+)

Enter fullscreen mode Exit fullscreen mode

The trade-off:

  • #!/bin/sh maximizes portability but limits you to POSIX. No arrays, no [[ ]], no local (technically not POSIX, though widely supported), no $(< file).
  • #!/usr/bin/env bash gives you all of bash's features but requires bash installed. On Alpine and FreeBSD, this means a bash package install before your script runs.
  • #!/bin/bash works on systems where bash is at /bin/bash (Linux, macOS). It does not work on NixOS or BSDs where bash is elsewhere.

For an installer script that needs to bootstrap itself, #!/bin/sh is the safest first line. Once you've checked for bash and installed it if needed, you can exec bash "$0 to re-exec under bash.

A real-world pattern:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

!/bin/sh

Bootstraps into bash if available, otherwise runs in POSIX sh.

if command -v bash >/dev/null 2>&1; then
# Re-exec under bash for arrays and [[ ]] but only if we're not already in bash.
case "$BASH_VERSION" in
"") exec bash "$0" "$@" ;;
esac
fi

Now we're either in bash or POSIX sh. Code accordingly.

set -eu

Enter fullscreen mode Exit fullscreen mode


shell

Strict Mode: set -euo pipefail

In bash:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
set -euo pipefail

Enter fullscreen mode Exit fullscreen mode


markdown

  • -e: exit on any command failure
  • -u: error on unset variable
  • -o pipefail: a pipeline fails if any command in it fails (default is to use the last command's exit code)

In POSIX sh, pipefail isn't available. The portable equivalent is to check each command explicitly or to wrap pipelines in functions that capture the exit code.

The gotcha with set -e: it doesn't trigger on commands in if, while, &&, ||, or !. That's by design-you want to test a command's exit code, not exit on it. But it means:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
set -e
false # script exits here
echo "never reached"

Enter fullscreen mode Exit fullscreen mode


plaintext

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
set -e
if false; then echo "x"; fi # script continues; false was tested, not run as a statement
echo "reached"

Enter fullscreen mode Exit fullscreen mode


shell

set -u catches typos in variable names but also catches legitimate uses of potentially-unset variables. The portable pattern for "use VAR if set, else default":

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

Bad under set -u: VAR might be unset

echo "$VAR"

Good: default empty

echo "${VAR:-}"

Good: default value

echo "${VAR:-default_value}"

Enter fullscreen mode Exit fullscreen mode


markdown

Detecting the OS

The portable way is to check uname -s first, then fall back to OS-specific files:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
detect_os() {
case "$(uname -s)" in
Darwin*) echo "macos" ;;
Linux*)
if [ -f /etc/alpine-release ]; then
echo "alpine"
elif [ -f /etc/debian_version ]; then
echo "debian"
elif [ -f /etc/redhat-release ]; then
echo "redhat"
elif [ -f /etc/arch-release ]; then
echo "arch"
else
echo "linux"
fi
;;
FreeBSD*) echo "freebsd" ;;
OpenBSD*) echo "openbsd" ;;
NetBSD*) echo "netbsd" ;;
MINGW*|MSYS*) echo "windows" ;; # Git Bash / MSYS2
CYGWIN*) echo "windows" ;;
*) echo "unknown" ;;
esac
}

OS="$(detect_os)"
echo "Detected OS: $OS"

Enter fullscreen mode Exit fullscreen mode


plaintext

uname -s returns Darwin on macOS, Linux on Linux, FreeBSD on FreeBSD, and MINGW64_NT-10.0 or similar on Git Bash. The case-glob handles the variants.

For the distro on Linux, /etc/os-release is the modern standard:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
detect_distro() {
if [ -f /etc/os-release ]; then
# shellcheck disable=SC1091
. /etc/os-release
echo "$ID"
elif [ -f /etc/alpine-release ]; then
echo "alpine"
elif [ -f /etc/debian_version ]; then
echo "debian"
elif [ -f /etc/redhat-release ]; then
echo "rhel"
else
echo "unknown"
fi
}

Enter fullscreen mode Exit fullscreen mode


markdown

/etc/os-release is the LSB-standardized way and is present on every modern Linux distro. The ID field gives you ubuntu, debian, alpine, fedora, centos, arch, etc.

Detecting Architecture

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
detect_arch() {
case "$(uname -m)" in
x86_64|amd64) echo "amd64" ;;
aarch64|arm64) echo "arm64" ;;
armv7l|armhf) echo "arm" ;;
i386|i686) echo "386" ;;
riscv64) echo "riscv64" ;;
ppc64le) echo "ppc64le" ;;
s390x) echo "s390x" ;;
*) echo "unknown" ;;
done
}

ARCH="$(detect_arch)"
echo "Detected arch: $ARCH"

Enter fullscreen mode Exit fullscreen mode


markdown

uname -m is portable across all Unix systems. The case aliases handle the naming inconsistencies: x86_64 on Linux, amd64 on FreeBSD/macOS; aarch64 on Linux, arm64 on macOS.

Package Manager Abstraction

Different platforms have different package managers. A real installer needs to abstract:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
install_packages() {
for pkg in "$@"; do
case "$OS" in
debian|ubuntu)
if ! dpkg -s "$pkg" >/dev/null 2>&1; then
DEBIAN_FRONTEND=noninteractive apt-get install -y "$pkg"
fi
;;
redhat|fedora|centos|rhel)
if ! rpm -q "$pkg" >/dev/null 2>&1; then
dnf install -y "$pkg"
fi
;;
alpine)
if ! apk info -e "$pkg" >/dev/null 2>&1; then
apk add --no-cache "$pkg"
fi
;;
arch)
if ! pacman -Q "$pkg" >/dev/null 2>&1; then
pacman -S --noconfirm "$pkg"
fi
;;
macos)
if ! brew list --formula "$pkg" >/dev/null 2>&1; then
brew install "$pkg"
fi
;;
freebsd)
if ! pkg info "$pkg" >/dev/null 2>&1; then
pkg install -y "$pkg"
fi
;;
*)
echo "Unsupported OS: $OS" >&2
return 1
;;
esac
done
}

Enter fullscreen mode Exit fullscreen mode


markdown

The pattern: check if the package is already installed before installing. This makes the script idempotent-running it twice doesn't reinstall everything.

Different distros use different package names for the same software. Common ones:

Software Debian/Ubuntu RHEL/Fedora Alpine macOS (brew)
OpenSSL dev libssl-dev openssl-devel openssl-dev openssl
curl curl curl curl curl
GNU sed sed sed sed gnu-sed
GNU tar tar tar tar gnu-tar
bash bash bash bash bash
build-essential build-essential gcc-c++ make build-base (xcode-select)
jq jq jq jq jq

The macOS column is where the abstraction gets ugly. brew's gnu-sed installs as gsed, not sed. You either alias it or use the BSD sed with its different flag conventions.

The BSD vs GNU Landmine

This is the part that bites everyone. The same command, different flags.

sed -i (in-place edit)

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

GNU sed (Linux)

sed -i 's/foo/bar/' file.txt

BSD sed (macOS)

sed -i '' 's/foo/bar/' file.txt

Busybox sed (Alpine)

sed -i 's/foo/bar/' file.txt # same as GNU

Enter fullscreen mode Exit fullscreen mode


plaintext

The portable pattern:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
sed_inplace() {
# Detects whether sed -i needs an argument
if sed --version 2>/dev/null | grep -q 'GNU sed'; then
sed -i "$@"
else
sed -i '' "$@"
fi
}

Enter fullscreen mode Exit fullscreen mode


plaintext

But this fails if "$@" already contains the script. A cleaner approach: don't use sed -i at all; write to a temp file and move.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
inplace_edit() {
local file="$1"; shift
local tmp
tmp="$(mktemp)"
sed "$@" "$file" > "$tmp" && mv "$tmp" "$file"
}

Enter fullscreen mode Exit fullscreen mode


plaintext

find -print0 / xargs -0

GNU find has -print0 and GNU xargs has -0. BSD find has -print0 too (modern BSDs), and BSD xargs has -0. Busybox find supports -print0 only if compiled with CONFIG_FEATURE_FIND_PRINT0. The portable pattern works almost everywhere:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
find . -name '*.log' -print0 | xargs -0 rm -f

Enter fullscreen mode Exit fullscreen mode


plaintext

But if you need -iname with extended regex, GNU find has -iregex, BSD find has -iregex too with different regex syntax. Don't rely on it.

date

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

GNU date (Linux)

date -d '2024-01-01' +%s
date -d 'yesterday' +%Y-%m-%d

BSD date (macOS)

date -j -f '%Y-%m-%d' '2024-01-01' +%s
date -v-1d +%Y-%m-%d

Busybox date

date -d '2024-01-01' +%s # supports -d, like GNU

Enter fullscreen mode Exit fullscreen mode


plaintext

The portable pattern for "yesterday":

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
yesterday() {
case "$OS" in
macos) date -v-1d +%Y-%m-%d ;;
*) date -d 'yesterday' +%Y-%m-%d ;;
esac
}

Enter fullscreen mode Exit fullscreen mode


plaintext

readlink -f (resolve symlinks)

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

GNU readlink

readlink -f /some/symlink

BSD readlink

readlink -f /some/symlink # works on modern macOS (11+)

Older BSD readlink has no -f; use realpath or a Python fallback

Enter fullscreen mode Exit fullscreen mode


plaintext

The bulletproof pattern:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
resolve_path() {
# Resolves symlinks and .. in $1 to an absolute path
if command -v realpath >/dev/null 2>&1; then
realpath "$1"
elif command -v readlink >/dev/null 2>&1 && readlink -f / >/dev/null 2>&1; then
readlink -f "$1"
else
# Fallback: Python
python3 -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$1"
fi
}

Enter fullscreen mode Exit fullscreen mode


markdown

Yes, the fallback is Python. Every modern Unix has Python 3 (or can install it in one command). It's an honest escape hatch when the shell layer is too fragmented.

The Pattern: A Real Installer Script

Putting it together. Here's a real installer pattern that's been battle-tested in installers for CLI tools:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

!/bin/sh

install-tool.sh - installs MyTool on any Unix-ish system

Usage: curl -fsSL https://example.com/install.sh | sh

Or: install-tool.sh [--version vX.Y.Z]

set -eu

----- constants -----

TOOL_NAME="mytool"
TOOL_REPO="example/mytool"
TOOL_VERSION="${1:---latest}"
INSTALL_DIR="${INSTALL_DIR:-${HOME}/.local/bin}"

----- color helpers (only if stderr is a TTY) -----

if [ -t 2 ] && command -v tput >/dev/null 2>&1; then
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
RESET=$(tput sgr0)
else
RED=""
GREEN=""
YELLOW=""
RESET=""
fi

log() { printf '%s[info]%s %s\n' "$GREEN" "$RESET" "$" >&2; }
warn() { printf '%s[warn]%s %s\n' "$YELLOW" "$RESET" "$
" >&2; }
error() { printf '%s[error]%s %s\n' "$RED" "$RESET" "$*" >&2; }

----- platform detection -----

detect_os() {
case "$(uname -s)" in
Darwin*) echo "macos" ;;
Linux*)
if [ -f /etc/alpine-release ]; then echo "alpine"
elif [ -f /etc/debian_version ]; then echo "debian"
elif [ -f /etc/redhat-release ]; then echo "redhat"
else echo "linux"
fi
;;
FreeBSD*) echo "freebsd" ;;
MINGW*|MSYS*|CYGWIN*) echo "windows" ;;
*) echo "unknown" ;;
esac
}

detect_arch() {
case "$(uname -m)" in
x86_64|amd64) echo "amd64" ;;
aarch64|arm64) echo "arm64" ;;
armv7l|armhf) echo "armv7" ;;
i386|i686) echo "i386" ;;
*) echo "unknown" ;;
esac
}

OS="$(detect_os)"
ARCH="$(detect_arch)"

if [ "$OS" = "unknown" ]; then
error "Unsupported OS: $(uname -s)"
exit 1
fi
if [ "$ARCH" = "unknown" ]; then
error "Unsupported arch: $(uname -m)"
exit 1
fi

log "Detected: $OS / $ARCH"

----- dependency check -----

need_cmd() {
if ! command -v "$1" >/dev/null 2>&1; then
error "Missing required command: $1"
case "$1" in
curl) warn " Install with: apt-get install curl (or your distro's equivalent)" ;;
tar) warn " Install with: apt-get install tar" ;;
*)
esac
exit 1
fi
}

need_cmd curl
need_cmd tar
need_cmd uname
need_cmd mktemp

----- resolve install dir -----

mkdir -p "$INSTALL_DIR"
case ":$PATH:" in
":$INSTALL_DIR:") : ;; # already in PATH
*)
warn "Install dir $INSTALL_DIR is not in your PATH."
warn "Add this to your shell config:"
warn " export PATH=\"$INSTALL_DIR:\$PATH\""
;;
esac

----- pick URL -----

case "$TOOL_VERSION" in
--latest)
API_URL="https://api.github.com/repos/$TOOL_REPO/releases/latest"
DOWNLOAD_URL=$(curl -fsSL "$API_URL" \
| grep -oE '"browser_download_url":\s*"[^"]'"$OS"'.'"$ARCH"'."' \
| head -1 \
| sed -e 's/.
"browser_download_url":\s*"//' -e 's/"$//')
if [ -z "$DOWNLOAD_URL" ]; then
error "No matching release asset for $OS/$ARCH"
exit 1
fi
;;
v*)
DOWNLOAD_URL="https://github.com/$TOOL_REPO/releases/download/$TOOL_VERSION/${TOOL_NAME}_${TOOL_VERSION}_${OS}_${ARCH}.tar.gz"
;;
*)
error "Invalid version: $TOOL_VERSION (expected --latest or vX.Y.Z)"
exit 1
;;
esac

----- download + extract -----

TMPDIR="$(mktemp -d)"
trap 'rm -rf "$TMPDIR"' EXIT INT TERM

log "Downloading $DOWNLOAD_URL"
TARBALL="$TMPDIR/${TOOL_NAME}.tar.gz"
curl -fsSL "$DOWNLOAD_URL" -o "$TARBALL"

log "Extracting"
tar -xzf "$TARBALL" -C "$TMPDIR"

Find the binary in the extracted contents

BINARY=""
for candidate in "$TMPDIR/$TOOL_NAME" "$TMPDIR/bin/$TOOL_NAME"; do
if [ -f "$candidate" ] && [ -x "$candidate" ]; then
BINARY="$candidate"
break
fi
done

if [ -z "$BINARY" ]; then
error "Binary not found in archive"
exit 1
fi

----- install -----

install -m 0755 "$BINARY" "$INSTALL_DIR/$TOOL_NAME"
log "Installed $TOOL_NAME to $INSTALL_DIR/$TOOL_NAME"

----- verify -----

if "$INSTALL_DIR/$TOOL_NAME" --version >/dev/null 2>&1; then
log "Verification: $("$INSTALL_DIR/$TOOL_NAME" --version)"
else
warn "Installed binary did not respond to --version"
fi

log "Done. Run: $TOOL_NAME --help"

Enter fullscreen mode Exit fullscreen mode


markdown

Note the patterns:

  • set -eu - strict mode for POSIX sh (no pipefail since it's not POSIX).
  • Colors only on TTY - so piping output to a log file doesn't fill it with escape codes.
  • trap ... EXIT - cleanup the temp dir on any exit path, including Ctrl-C.
  • need_cmd - fail early with a helpful message, not three steps later with a cryptic error.
  • command -v - POSIX, not which (which isn't POSIX and behaves differently across platforms).
  • case "$OS" in ... esac - switch on the detected OS, with a default error case.
  • PATH check - warn (not fail) if the install dir isn't on PATH, with a copy-pasteable fix.

This script runs on Debian, Ubuntu, Alpine, Fedora, CentOS, Arch, macOS, and FreeBSD. It needs curl, tar, and a POSIX shell. Nothing else.

Common Mistakes

Using which instead of command -v. which is a separate binary, not a shell builtin, and its output format varies. command -v is POSIX and returns just the path or nothing. Use command -v foo >/dev/null 2>&1 for "is foo installed."

bash features under #!/bin/sh. Symptom: "syntax error: bad substitution." You used [[ ]], ${var,,} (lowercase), or arrays under a non-bash shell. Fix: switch shebang to #!/usr/bin/env bash or rewrite to POSIX.

CRLF line endings. Symptom: bash: \r: command not found or #!/bin/sh\r: no such file or directory. The file was edited on Windows. Fix: dos2unix file.sh or sed -i 's/\r$//' file.sh. Configure git: git config --global core.autocrlf input.

Unquoted variables. Symptom: script breaks on filenames with spaces. for f in $(ls) is the classic. Fix: for f in *; do ... or use find ... -print0 | while IFS= read -r f; do ....

read without -r. Symptom: backslashes in input disappear. Fix: IFS= read -r line.

Assuming ls output is parseable. ls adds color codes, sorts differently, splits filenames on whitespace. Use globs (for f in *.txt) or find.

Using sudo inside scripts. Symptom: script asks for password mid-run, fails in CI. Fix: document that the user should run with sudo, or use sudo only on the specific commands that need it, or check for root and exit with a message.

exit 1 in a pipe. Symptom: pipeline continues even after a failure. Fix: set -o pipefail (bash) or check each command's exit code explicitly.

Hardcoding /usr/local/bin. Symptom: script fails on systems where /usr/local/bin doesn't exist or isn't writable. Fix: use ${PREFIX:-/usr/local} and mkdir -p.

Testing with shellcheck and shellspec

shellcheck

shellcheck is non-negotiable. It catches 90% of shell bugs automatically. Install:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

Linux

sudo apt install shellcheck

macOS

brew install shellcheck

Or via cargo / npm if you prefer

Enter fullscreen mode Exit fullscreen mode


plaintext

Run on every script:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
shellcheck --severity=warning myscript.sh

Enter fullscreen mode Exit fullscreen mode


plaintext

For CI, add to your GitHub Actions:

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

.github/workflows/shellcheck.yml

name: shellcheck
on: [push, pull_request]
jobs:
shellcheck:
runs-on: ubuntu-latest
steps:

  • uses: actions/checkout@v4
  • uses: ludeeus/action-shellcheck@master with: severity: warning format: gcc
Enter fullscreen mode Exit fullscreen mode


plaintext

Inline directive to ignore a specific warning:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell

shellcheck disable=SC2086 # we want word splitting here

curl $URL

Enter fullscreen mode Exit fullscreen mode


markdown

Use sparingly-every disable is a place you've decided shellcheck is wrong.

shellspec

For non-trivial scripts, shellspec gives you real unit tests. Install:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
curl -fsSL https://git.io/shellspec | sh -s -- --prefix ~/.local

Enter fullscreen mode Exit fullscreen mode


plaintext

A simple test for our detect_arch function:

ShellCopy

Enter fullscreen mode Exit fullscreen mode


shell

spec/detect_arch_spec.sh

Describe 'detect_arch'
# Source the script under test, but mock uname
Before 'setup_mock'

setup_mock() {
# Mock uname to return a fixed value
uname() {
case "$1" in
-m) echo "x86_64" ;;
-s) echo "Linux" ;;
*) /usr/bin/uname "$@" ;;
esac
}
}

It 'returns amd64 for x86_64'
When call detect_arch
The output should equal "amd64"
End
End

Enter fullscreen mode Exit fullscreen mode


plaintext

Run with:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
shellspec

Enter fullscreen mode Exit fullscreen mode


markdown

For a script that's mostly glue (curl + tar + mv), shellspec is overkill. For a script with real logic-parsing, branching, format conversion-it's worth the investment.

CI Matrix: Test on Multiple Platforms

The single best thing you can do for cross-platform scripts is run them on multiple platforms in CI:

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

.github/workflows/test-script.yml

name: test-script
on: [push, pull_request]
jobs:
shellcheck:
runs-on: ubuntu-latest
steps:

  • uses: actions/checkout@v4
  • uses: ludeeus/action-shellcheck@master

test:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest]
shell: [sh, bash, dash]
exclude:

  • os: macos-latest shell: dash # dash isn't installed on macOS by default runs-on: ${{ matrix.os }} steps:
  • uses: actions/checkout@v4
  • name: Install dash on Linux if: matrix.os == 'ubuntu-latest' && matrix.shell == 'dash' run: sudo apt-get install -y dash
  • name: Run script run: ${{ matrix.shell }} ./install-tool.sh --dry-run
Enter fullscreen mode Exit fullscreen mode


plaintext

For Alpine, add a separate job using a container:

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml
test-alpine:
runs-on: ubuntu-latest
container: alpine:latest
steps:

  • uses: actions/checkout@v4
  • name: Install bash for tests run: apk add --no-cache bash
  • name: Run script with sh (ash) run: sh ./install-tool.sh --dry-run
  • name: Run script with bash run: bash ./install-tool.sh --dry-run
Enter fullscreen mode Exit fullscreen mode


markdown

For FreeBSD, GitHub Actions doesn't natively support it. Use a self-hosted runner or a service likecirrus-ci. The same script logic applies.

The matrix catches the BSD-vs-GNU issues that you can't catch on a Linux-only CI.

Production Considerations

Idempotency. Your script should be safe to run twice. Check before you install, check before you create. mkdir -p, touch, install are all idempotent; mv, rm aren't.

Atomic writes. Don't write directly to a target file. Write to a temp file, then move. mv is atomic on the same filesystem; if the script fails partway through, you don't end up with a half-written config.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
tmp=$(mktemp)
cat > "$tmp" <<EOF
...
EOF
mv "$tmp" /etc/myapp/config.conf

Enter fullscreen mode Exit fullscreen mode


plaintext

Temp file cleanup. Always trap EXIT:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

Enter fullscreen mode Exit fullscreen mode


markdown

Without this, a Ctrl-C leaves temp files behind. Over months, your /tmp fills up.

Logging. Write to a log file in addition to stdout. Include timestamps. Don't use echo for errors-use printf '%s\n' "$msg" >&2. Errors go to stderr; info goes to stdout. Piping your script to a log file should not lose the errors.

Privilege separation. If your script needs root, do the root things in a sub-shell with sudo, not the whole script as root. This way, if you have a bug in the non-root parts, you don't run it as root.

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
if [ "$(id -u)" -ne 0 ]; then
# Re-exec as root only the parts that need it
sudo sh -c "$ROOT_INSTALL_COMMANDS"
fi

Enter fullscreen mode Exit fullscreen mode

Secrets. Don't bake secrets into scripts. Read from env vars or a config file with 0600 permissions. If you must embed a token in a script (e.g., for an installer that downloads from a private repo), assume it will leak-rotate it regularly.

Real-World Use Cases

Installer scripts for CLI tools. The pattern in this article. Used by Homebrew's install.sh, rustup's init.sh, nvm's install script, pyenv, asdf. All of them detect OS, detect arch, install dependencies if needed, download the right binary, and verify.

CI build scripts. A scripts/build.sh that runs on dev laptops and CI runners. Detects if it's in CI (${CI:-} env var), picks the right build flags, runs the build, runs tests. The same script on macOS dev and Linux CI.

Bootstrap scripts for new machines. A setup.sh that installs brew on macOS, apt packages on Debian, configs from a dotfiles repo. Runs once on a new machine, makes it usable.

Health check scripts. A healthcheck.sh that the monitoring system calls. Checks disk space, memory, key processes, returns 0 healthy / 1 unhealthy. Same script across all servers.

Deployment scripts. Pull the latest image, restart the service, verify it's healthy. The script needs to work whether you're on the dev box or the prod box, with the right env vars loaded.

Alternatives and Comparison

Approach Strength Weakness Best for
POSIX sh Maximum portability No arrays, no [[ ]] Installers, simple glue
Bash Features, ubiquitous on Linux Not on Alpine/BSD by default Anything on Linux servers
Python Real language, stdlib Adds runtime dependency Anything complex
Go compiled binary Single file, no deps Compile per platform CLI tools
Rust compiled binary Single file, fast Compile per platform, slower compile CLI tools
Make Declarative, ubiquitous Cross-platform Makefiles are painful Build orchestration
Just (justfile) Modern make Adds dependency Dev workflows
Taskfile (yaml) Cross-platform, no shell quoting YAML, learning curve Dev workflows

For a script that's a few hundred lines and runs in CI, shell is the right answer. For something that needs real data structures, error handling, and tests, reach for Python or a compiled binary. The mistake is staying in shell too long-1000-line shell scripts are a nightmare to maintain.

Cost Considerations

Shell scripts are free. The cost is in time-yours, debugging, and your users', hitting edge cases you didn't anticipate.

Investment Time Return
Learn POSIX sh basics 4 hours Catches 50% of portability bugs
Read shellcheck warnings 2 hours/script Catches 80% of common bugs
Set up CI matrix 2 hours Catches the BSD/GNU issues
Write shellspec tests 1 day/script Only worth it for non-trivial logic
Migrate to Python Days Worth it when the script crosses 500 lines

The honest recommendation: shell for ≤200 lines, Python or Go for longer. The boundary isn't a hard rule, but it's a good heuristic. Once you're maintaining a 1000-line bash script with custom argument parsing and structured output, you're fighting the language.

Best Practices Summary

  • Start with #!/bin/sh and set -eu. Switch to bash only when you need a feature.
  • Always quote variables. "$var", not $var.
  • Use command -v, not which.
  • Trap EXIT for cleanup.
  • Detect OS and arch explicitly; don't assume.
  • Abstract package managers behind a function.
  • Use mktemp for temp files, not /tmp/scriptname.$$.
  • Atomic writes: temp file + mv.
  • Errors to stderr: printf '%s\n' "$msg" >&2.
  • Idempotent operations: check before install/create.
  • Run shellcheck in CI, every commit.
  • Test on at least Linux + macOS in CI.

Conclusion

Cross-platform shell scripting is a craft. The tools are simple, the environment is fragmented, and the bugs are subtle. The winning approach is to start from POSIX, detect what you're running on, abstract the differences, and test on multiple platforms in CI. shellcheck catches the easy bugs; CI matrices catch the platform-specific ones; the rest is reading the BSD and GNU man pages side by side and sighing. Once you've internalized the patterns, you'll write a single installer that works on Debian, Alpine, macOS, and FreeBSD, and the next "works on my machine" bug won't be yours.


Originally published on Mango Developer.

Top comments (0)