Writing Portable Shell Scripts

Su Suriya Ravichandran Updated 06 Dec 2026
15 min read ·Lesson 188 of 205

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:

  1. The shell that interprets it. /bin/sh is Dash on Debian and Ubuntu, BusyBox ash on 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.
  2. The external commands it calls. sed, grep, date, find and stat exist 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:

SituationSensible targetShebang
Developer tools and automation on machines you control, all with modern BashBash (state the minimum version)#!/usr/bin/env bash
Scripts that must also run on macOS's stock BashBash 3.2 features only#!/usr/bin/env bash
Installers, container entrypoints, scripts for Alpine, embedded systems or unknown machinesPOSIX 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:

TaskGNU (Linux) onlyPortable alternative
Edit a file in placesed -i 's/a/b/' f (BSD sed requires sed -i '' ...)sed 's/a/b/' f > f.tmp && mv -- f.tmp f
Date arithmeticdate -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 filereadlink -f (missing on older macOS)cd -- "$(dirname -- "$f")" && pwd -P
Perl-style regular expressionsgrep -Pgrep -E with POSIX character classes
File sizestat -c %s f (BSD uses stat -f %z)wc -c < f
Number sequenceseq 1 10 (not a POSIX utility)a while loop with $(( ))
Leading-option stylehead -5, tail +2head -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 mv for 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=C makes 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/sh is honest: the script uses only POSIX features, so any sh can run it.
  • getopts is the POSIX option parser (lesson 130); it is a shell built-in everywhere, unlike the external getopt command, whose GNU and BSD versions differ.
  • Sorting without sort or ls. 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, and LC_ALL=C guarantees that every system sorts the same way. Parsing the output of ls -t would 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 named backup-*.tar.gz. [ -e "$f" ] || continue skips it. Bash's nullglob option (lesson 149) would solve this more elegantly, but it is not available in sh.
  • ${f##*/} removes the directory part using POSIX parameter expansion, instead of calling basename for 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.sh is the quickest check for Bash features, because Dash implements little beyond POSIX. Running the test suite (lessons 185 to 187) with dash instead of bash catches 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-based prune-bash.sh above runs without complaint under bash --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=sh forces that check. The checkbashisms tool from Debian's devscripts package 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/backups for 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.

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 Writing Portable Shell Scripts and get answers drawn from it.

Signed-in readers only.