Writing Portable Shell Scripts
A portable shell script is one that runs correctly on more than one kind of system without changes. That sounds simple, because "a shell script" seems like one thing. In reality, a script depends on two separate layers that vary between systems:
- The shell that interprets it.
/bin/shis Dash on Debian and Ubuntu, BusyBoxashon Alpine Linux (common in Docker images), Bash on Fedora and Red Hat, and Bash 3.2 running in POSIX mode on macOS. Even "Bash" is not one target: macOS still ships Bash 3.2 from 2007 as/bin/bash, while current Linux distributions ship Bash 5. - The external commands it calls.
sed,grep,date,findandstatexist almost everywhere, but Linux uses the GNU versions, macOS and the BSDs use BSD versions, and Alpine uses BusyBox versions. Their common core is the same; their options are not.
A script written and tested on one Ubuntu laptop can break in a CI container, on a colleague's Mac or on a minimal server, usually with a confusing error. This lesson explains how to decide how portable a script needs to be, which shell features and command options are safe, and how to test a script on the shells it claims to support.
Deciding What "Portable" Means for a Script
Portability is not a goal in itself; it is a requirement that comes from where the script runs. Three common situations lead to three different choices:
| Situation | Sensible target | Shebang |
|---|---|---|
| Developer tools and automation on machines you control, all with modern Bash | Bash (state the minimum version) | #!/usr/bin/env bash |
| Scripts that must also run on macOS's stock Bash | Bash 3.2 features only | #!/usr/bin/env bash |
| Installers, container entrypoints, scripts for Alpine, embedded systems or unknown machines | POSIX sh | #!/bin/sh |
The POSIX standard (Portable Operating System Interface) defines a shell language and a set of utilities with their options. Every shell that claims to be sh implements this language, so a script limited to POSIX features runs under Dash, BusyBox, Bash, ksh and zsh in sh mode alike.
The most important rule follows directly from the table: the shebang must match the features the script uses. A script that uses Bash features must say bash, never sh. The opposite mistake is extremely common, because on many systems sh used to be Bash, so a Bash script labelled #!/bin/sh happened to work for years.
What Goes Wrong: A Bash Script Run as sh
The following script keeps the newest backups in a directory and deletes the rest. It uses Bash arrays and arithmetic, but its first line claims it is an sh script:
#!/bin/sh
# prune-bash.sh - keep the newest KEEP backups (written with Bash features)
dir=${1:?usage: prune-bash.sh DIR [KEEP]}
keep=${2:-3}
files=( "$dir"/backup-*.tar.gz )
(( ${#files[@]} > keep )) || { echo "nothing to prune"; exit 0; }
for f in "${files[@]:0:${#files[@]}-keep}"; do
echo "removing ${f##*/}"
rm -- "$f"
done
Run explicitly with Bash, it works. Run the way its shebang asks, on Ubuntu where /bin/sh is Dash, it fails before doing anything:
$ bash prune-bash.sh b 4
removing backup-20261125-0200.tar.gz
removing backup-20261126-0200.tar.gz
$ ./prune-bash.sh b 4
./prune-bash.sh: 5: Syntax error: "(" unexpected
Dash does not know arrays, so files=( is a syntax error on line 5. This failure is at least loud. Other differences are silent and more dangerous, because the script keeps running with different behavior. Here are a few Bash features tried in Dash:
$ dash -c '[[ a == a ]] && echo yes'
dash: 1: [[: not found
$ dash -c 'x=abc; echo ${x//b/X}'
dash: 1: Bad substitution
$ dash -c 'echo {1..3}'
{1..3}
$ dash -c 'x=5; ((x++)); echo $x'
dash: 1: x++: not found
5
$ dash -c 'source /dev/null && echo source ok'
dash: 1: source: not found
Look at the brace expansion and the arithmetic: {1..3} is printed literally, so a loop over it would run once with the string {1..3}; ((x++)) is read as two nested subshells running a command called x++, so the counter silently stays at 5. In a script without set -e, execution continues with wrong values. Lesson 189 lists the Bash features and their POSIX replacements systematically; this lesson concentrates on the habits and techniques that make a whole script portable.
The Portable Shell Toolkit
POSIX sh is smaller than Bash, but it contains everything needed for solid scripts. The following building blocks cover most needs.
printf Instead of echo
echo is the least portable command in shell scripting, because shells disagree about whether it interprets backslash escapes and which options it accepts:
$ bash -c "echo 'a\tb|'"
a\tb|
$ dash -c "echo 'a\tb|'"
a b|
$ dash -c 'echo -e "x\ty"'
-e x y
Bash prints the backslash literally; Dash turns \t into a tab. Dash does not know -e and prints it as text, which is a classic sign of a Bash-only script running under sh. printf behaves the same everywhere, because its format string rules are standardized:
printf '%s\n' "$message" # print a variable exactly as it is
printf 'Saved %d files to %s\n' "$count" "$dir"
printf '%s' "no newline at the end"
Use echo only for fixed text without backslashes or leading dashes, and printf '%s\n' for anything that contains variables.
Tests with [ ] and case
[[ ]] is a Bash keyword. The POSIX test command, written [ ], does the same basic job, with three rules: always quote variables, use = (not ==) for string comparison, and combine conditions with && and || between separate tests rather than the obsolete -a and -o operators:
if [ -f "$config" ] && [ "$mode" = "production" ]; then
printf 'using %s\n' "$config"
fi
For pattern matching, which [[ $x == *.txt ]] does in Bash, use case. It is POSIX, fast and readable:
case $file in
*.tar.gz|*.tgz) kind=archive ;;
*.txt) kind=text ;;
*) kind=other ;;
esac
case also validates input without any external command. The pattern ''|*[!0-9]* matches an empty string or anything containing a non-digit, which makes a simple and portable integer check:
case $keep in
''|*[!0-9]*) die "KEEP must be a non-negative integer: $keep" ;;
esac
Arithmetic with $(( ))
Arithmetic expansion $(( )) is POSIX; the (( )) command and let are not. Use $(( )) for calculations and [ ] with -lt, -gt and friends for numeric comparisons:
remove=$((total - keep))
[ "$remove" -gt 0 ] || exit 0
count=$((count + 1)) # instead of ((count++))
Lists Without Arrays: the Positional Parameters
POSIX sh has no arrays, but it has one list that keeps every element intact: the positional parameters "$@". set -- replaces them with new values, so a script can build a list of file names, including names with spaces, safely:
set -- # start with an empty list
for f in "$dir"/backup-*.tar.gz; do
[ -e "$f" ] || continue # the pattern matched nothing
set -- "$@" "$f" # append one element
done
printf 'found %d backups\n' "$#"
for f in "$@"; do printf '%s\n' "$f"; done
Since there is only one such list, save the script's own arguments into variables first. For lists that need more structure, write them to a temporary file, one item per line, or let a tool like awk do the work.
Functions and Variables
Define functions as name() { ...; }. The function keyword is not POSIX and is a syntax error in Dash. local is not part of POSIX either, but Dash, BusyBox ash, Bash and zsh all support it, so most portable scripts use it; only scripts that must run under ksh93, which uses typeset inside functions instead, need to avoid it. Load other files with . instead of source:
. "$script_dir/lib.sh"
Locating Commands and the Script Itself
which is an external program whose output and exit status differ between systems. command -v is the POSIX way to ask whether a command exists:
command -v gzip >/dev/null 2>&1 || die "gzip is required"
To find the directory the script lives in, Bash scripts often use $BASH_SOURCE or readlink -f, neither of which is portable. This idiom works in every POSIX shell and resolves symbolic links in the directory path:
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
CDPATH= prevents a user's CDPATH setting from making cd print a directory name into the result; -- protects against names starting with a dash; pwd -P prints the physical path without symbolic links. Run through a symbolic link named link that points to deep dir/x, the script reports the real location:
$ dash /path/to/link/where.sh
script lives in /path/to/deep dir/x
Strict Mode in POSIX sh
set -e and set -u are POSIX and behave in Dash as in Bash. set -o pipefail was only added to the POSIX standard in its 2024 edition, and many installed shells do not support it yet. Dash 0.5.12, the version in Ubuntu 24.04, rejects it:
$ dash -c 'set -o pipefail && echo ok'
dash: 1: set: Illegal option -o pipefail
A portable script therefore starts with set -eu and handles pipelines whose left side can fail explicitly. One reliable technique writes the producer's status to a temporary file:
#!/bin/sh
# pipe-status.sh - detect a failure on the left side of a pipeline without pipefail
set -eu
generate_report() {
printf 'line 1\nline 2\n'
return 3 # simulate a failure after partial output
}
status_file=$(mktemp)
trap 'rm -f "$status_file"' EXIT
{ rc=0; generate_report || rc=$?; echo "$rc" > "$status_file"; } | gzip > report.gz
read -r gen_status < "$status_file"
if [ "$gen_status" -ne 0 ]; then
printf 'report generation failed with status %s\n' "$gen_status" >&2
rm -f report.gz
exit 1
fi
echo "report written"
$ dash pipe-status.sh; echo "status $?"
report generation failed with status 3
status 1
The detail rc=0; generate_report || rc=$? matters. The first version of this example wrote { generate_report; echo "$?" > "$status_file"; }, and it failed in a confusing way: because of set -e, the left side of the pipeline stopped as soon as generate_report returned 3, so the status was never written, read hit an empty file, and the script exited with status 1 without any message, leaving the incomplete report.gz behind. Putting the call on the left of || exempts it from set -e and stores its status reliably.
Traps and Signals
trap is POSIX, but signal names must be written without the SIG prefix. Bash accepts both forms; Dash rejects the prefixed one and continues without installing the trap:
$ dash -c 'trap "echo bye" SIGINT; echo ok'
trap: SIGINT: bad trap
ok
Write trap cleanup INT TERM and trap 'rm -f "$tmp"' EXIT.
Portable Use of External Commands
Shell syntax is only half of the problem. A script that is perfect POSIX sh still breaks on macOS if it calls sed -i the GNU way. These are the differences that cause most real-world failures:
| Task | GNU (Linux) only | Portable alternative |
|---|---|---|
| Edit a file in place | sed -i 's/a/b/' f (BSD sed requires sed -i '' ...) | sed 's/a/b/' f > f.tmp && mv -- f.tmp f |
| Date arithmetic | date -d '2 days ago' (BSD uses date -v-2d) | let find -mtime +2 select old files, or compute with date +%s |
| Absolute path of a file | readlink -f (missing on older macOS) | cd -- "$(dirname -- "$f")" && pwd -P |
| Perl-style regular expressions | grep -P | grep -E with POSIX character classes |
| File size | stat -c %s f (BSD uses stat -f %z) | wc -c < f |
| Number sequence | seq 1 10 (not a POSIX utility) | a while loop with $(( )) |
| Leading-option style | head -5, tail +2 | head -n 5, tail -n +2 |
Three habits prevent most of these problems:
- Stick to options listed in the POSIX specification of a command when portability matters. GNU manual pages mark many extensions; when unsure, compare with the BSD manual page or the POSIX text.
- Prefer a temporary file plus
mvfor in-place edits. It is portable and also safer, because the original stays untouched if the edit fails. - Set the locale for sorting and matching. Sorting order and character ranges like
[a-z]depend on the locale;LC_ALL=Cmakes them byte-based and identical on every system.
The temporary-file edit works the same everywhere:
$ printf 'host=old\n' > cfg
$ sed 's/old/new/' cfg > cfg.tmp && mv -- cfg.tmp cfg
$ cat cfg
host=new
A Complete Portable Script
Here is the backup pruning script rewritten for POSIX sh, with options, validation and a dry-run mode:
#!/bin/sh
#
# prune-backups.sh - delete old backup archives, keeping the newest ones
#
# Usage: prune-backups.sh [-n] [-k KEEP] DIR
#
# -k KEEP number of newest backups to keep (default 7)
# -n dry run: show what would be deleted, delete nothing
#
# Backups are files named backup-YYYYMMDD-HHMM.tar.gz, so sorting the
# names also sorts them by age. Written for POSIX sh: runs under dash,
# BusyBox ash, bash, ksh and zsh in sh mode.
set -eu
LC_ALL=C # byte-wise sorting, the same on every system
export LC_ALL
prog=${0##*/}
keep=7
dry_run=0
die() {
printf '%s: %s\n' "$prog" "$*" >&2
exit 1
}
usage() {
printf 'Usage: %s [-n] [-k KEEP] DIR\n' "$prog" >&2
exit 2
}
while getopts 'nk:' opt; do
case $opt in
n) dry_run=1 ;;
k) keep=$OPTARG ;;
*) usage ;;
esac
done
shift $((OPTIND - 1))
[ "$#" -eq 1 ] || usage
dir=$1
case $keep in
''|*[!0-9]*) die "KEEP must be a non-negative integer: $keep" ;;
esac
[ -d "$dir" ] || die "not a directory: $dir"
# Collect the backups as positional parameters: POSIX sh has no arrays,
# but "$@" is a list that keeps every name intact, spaces included.
set --
for f in "$dir"/backup-*.tar.gz; do
[ -e "$f" ] || continue # the pattern matched nothing
set -- "$@" "$f"
done
total=$#
if [ "$total" -le "$keep" ]; then
printf '%s: %d backup(s), keeping all\n' "$prog" "$total"
exit 0
fi
remove=$((total - keep))
printf '%s: %d backup(s), removing the oldest %d\n' "$prog" "$total" "$remove"
# Glob results are sorted, so the oldest backups come first.
for f in "$@"; do
[ "$remove" -gt 0 ] || break
if [ "$dry_run" -eq 1 ]; then
printf 'would remove %s\n' "${f##*/}"
else
rm -f -- "$f"
printf 'removed %s\n' "${f##*/}"
fi
remove=$((remove - 1))
done
How the Script Stays Portable
#!/bin/shis honest: the script uses only POSIX features, so anyshcan run it.getoptsis the POSIX option parser (lesson 130); it is a shell built-in everywhere, unlike the externalgetoptcommand, whose GNU and BSD versions differ.- Sorting without
sortorls. The POSIX standard requires pathname expansion results to be sorted. Because the timestamps in the names run from year to minute, alphabetical order is chronological order, andLC_ALL=Cguarantees that every system sorts the same way. Parsing the output ofls -twould be both less portable and unsafe with unusual file names. - The unmatched-glob check. If no file matches
backup-*.tar.gz, POSIX shells leave the pattern unchanged, so the loop would see one "file" literally namedbackup-*.tar.gz.[ -e "$f" ] || continueskips it. Bash'snullgloboption (lesson 149) would solve this more elegantly, but it is not available insh. ${f##*/}removes the directory part using POSIX parameter expansion, instead of callingbasenamefor every file.rm -f -- "$f":--ends option processing, so a file name starting with a dash cannot be mistaken for an option.
Running It in Several Shells
A test directory with six backups and an unrelated file (the directory name contains a space on purpose) was pruned to four backups with each available shell. All produce the same result:
== dash
prune-backups.sh: 6 backup(s), removing the oldest 2
removed backup-20261125-0200.tar.gz
removed backup-20261126-0200.tar.gz
status 0
backup-20261127-0200.tar.gz backup-20261128-0200.tar.gz backup-20261129-0200.tar.gz backup-20261130-0200.tar.gz notes.txt
== bash
prune-backups.sh: 6 backup(s), removing the oldest 2
removed backup-20261125-0200.tar.gz
removed backup-20261126-0200.tar.gz
status 0
backup-20261127-0200.tar.gz backup-20261128-0200.tar.gz backup-20261129-0200.tar.gz backup-20261130-0200.tar.gz notes.txt
The error paths behave consistently as well:
$ ./prune-backups.sh -n -k 5 bk
prune-backups.sh: 6 backup(s), removing the oldest 1
would remove backup-20261125-0200.tar.gz
$ ./prune-backups.sh -k two bk; echo "status $?"
prune-backups.sh: KEEP must be a non-negative integer: two
status 1
$ ./prune-backups.sh empty; echo "status $?"
prune-backups.sh: 0 backup(s), keeping all
status 0
$ ./prune-backups.sh -x bk; echo "status $?"
Illegal option -x
Usage: prune-backups.sh [-n] [-k KEEP] DIR
status 2
The last example shows a harmless remaining difference: the message for an unknown option comes from getopts itself, and its wording depends on the shell. Dash prints Illegal option -x, Bash prints illegal option -- x. Scripts that need identical messages everywhere start the option string with a colon (getopts ':nk:' opt), which silences the built-in message and lets the script print its own.
Testing Portability
A script is only as portable as the shells it has actually been run with. Claims like "POSIX compliant" in a header comment mean nothing until the script has been tested against them.
- Run it with Dash. On Debian and Ubuntu,
dash script.shis the quickest check for Bash features, because Dash implements little beyond POSIX. Running the test suite (lessons 185 to 187) withdashinstead ofbashcatches most problems in seconds. - Do not rely on
bash --posix. POSIX mode changes some Bash behaviors to match the standard, but it does not disable Bash extensions: the array-basedprune-bash.shabove runs without complaint underbash --posix. It is not a portability test. - Use static analysis. ShellCheck (lessons 162 and 190) reads the shebang and warns about Bash features used in a script declared as
sh;shellcheck --shell=shforces that check. Thecheckbashismstool from Debian'sdevscriptspackage does a similar job. - Test on the real targets. Containers make other environments cheap to try, for example
docker run --rm -v "$PWD:/src" -w /src alpine sh ./prune-backups.sh -n /src/backupsfor BusyBox. For macOS, a CI job on a macOS runner (lesson 177) is the most reliable way to catch BSD tool differences.
The next lesson goes through the differences between Bash syntax and POSIX syntax one by one, with the POSIX replacement for each Bash feature, so that converting a script like prune-bash.sh becomes a mechanical task.