Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 95 ยท Advanced Bash

POSIX sh, Portability and Compatibility

Learn the difference between bash, sh, dash and zsh, find bashisms, write portable POSIX scripts, handle GNU versus BSD tools, and use shellcheck and feature detection.

"Shell script" is not one language. Your scripts may run under Bash 5 on your laptop, dash as /bin/sh on Debian and Ubuntu, BusyBox ash in a container, Bash 3.2 on a Mac, or zsh as the macOS login shell. A script written and tested only in one of them can fail in surprising ways in another: a syntax error on the first line, silently different output, or an option that does not exist.

This lesson gives you the map: what POSIX sh is, which Bash features are extensions (bashisms), how to find them, how to write scripts that run everywhere when you need to, and how to deal with the other big portability problem, the tools (GNU on Linux, BSD on macOS). It also tells you when portability is not worth the effort. In our sandbox we have Bash 5.0, dash and ksh93, so every claim below is tested on the three of them.

The shells and who uses what

Shell Where you meet it Notes
POSIX sh The standard A specification, not one program. The common denominator.
dash /bin/sh on Debian, Ubuntu Small and fast; implements POSIX and little else.
bash Login shell on most Linux; /bin/sh on Fedora, RHEL, Arch (in POSIX mode) POSIX plus many extensions. macOS ships 3.2 (2007) because of licensing.
zsh Default login shell on macOS since 2019 Similar to bash for simple things, different for arrays and word splitting.
ksh93 Commercial Unix, some BSDs Bash borrowed many features from it.
ash / BusyBox sh Alpine Linux, embedded devices, many containers Close to dash.

What matters is which shell executes your file. That is decided by the shebang line (#!/bin/bash, #!/usr/bin/env bash, #!/bin/sh) when you run ./script, but by the command you type when you run sh script.sh or bash script.sh: the shebang is then only a comment. Let's look at what is installed here and how a script can tell what runs it.

Bash Which shell is which

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first run shows that #!/bin/sh on this system is not Bash. This is the root of the most common portability bug: a script with #!/bin/sh that uses Bash features works on Fedora (where /bin/sh is Bash) and breaks on Ubuntu (where it is dash).

Bashisms: what dash and ksh do not accept

A bashism is any feature beyond POSIX sh that Bash provides. Here is a test bench: each line is a small snippet, run through Bash, dash and ksh93, and compared with Bash's output.

Bash A bashism test bench across three shells

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Read the table column by column. Anything that says error is a syntax error or a missing feature; differs is worse: the command runs, but behaves differently, so the bug hides. Typical findings:

  • [[ ... ]], arrays, <<<, <( ), (( )), for (( ... )), ${var^^}, ${var/a/b}, set -o pipefail and $EPOCHSECONDS are Bash/ksh extensions that dash lacks (ksh93 has most of them, but not all, and not with identical syntax).
  • == inside [ ] is a bashism too; POSIX test has only =.
  • echo -e differs: dash prints a literal -e and always interprets backslashes. echo $'a\tb' shows that $'...' quoting is also an extension.
  • {1..3} does not expand in dash (it prints the braces).
  • ** in arithmetic is not POSIX.

The POSIX equivalents, which work in all of them:

Bash style Portable POSIX version
[[ $a == b* ]] case $a in b*) ... ;; esac
[[ $a == "$b" ]] and [ a == b ] [ "$a" = "$b" ]
[[ -n $x && -f $y ]] [ -n "$x" ] && [ -f "$y" ]
echo -e "a\tb", echo -n printf 'a\tb\n'
source file . ./file
function f { ...; } f() { ...; }
${x/a/b}, ${x^^} sed, tr, or case
<<< "$s" printf '%s\n' "$s" | or a here-doc
arrays positional parameters (set -- a b c; for x in "$@"), or newline-separated text
$(( 2**3 )) repeated multiplication, or awk
x=$(< file) x=$(cat file)
set -o pipefail no portable equivalent; check statuses explicitly (pipefail is in POSIX 2024, but not in older shells)
local v not in POSIX. dash, ash and bash have it; ksh93 does not (local: not found, it uses typeset)
read -r -p "msg" v printf 'msg'; read -r v
type -t, which command -v name

Notice also local in the bench: it is not in the POSIX standard. dash, BusyBox ash and Bash all provide it, so using it in #!/bin/sh scripts for Linux is a calculated, widely accepted risk; ksh93 does not have it (the bench shows differs, because the function silently fails to set the variable), and neither do some commercial Unix shells. If you need to be strictly portable, use unique variable names or run the function body in a subshell: f() ( ... ).

Writing a portable script

A short example in strictly POSIX style: no arrays, no [[, only printf and case, command -v for existence checks. We run the very same file under dash, bash and ksh and compare the outputs.

Bash One POSIX script, three shells, identical output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The code uses only POSIX constructs, so the three shells print the same lines (the uniq -c check shows that each line appears three times). ${#word} (string length), ${0##*/} (basename) and $(( )) are all POSIX, as is case with character classes such as [!A-Za-z].

Make your intent explicit

  • Use #!/bin/sh only if you really restrict yourself to POSIX, and test with dash (dash script.sh). Use #!/usr/bin/env bash when you want Bash features; that finds Bash wherever it is installed (on macOS, a Homebrew Bash 5 in /opt/homebrew/bin or /usr/local/bin; /bin/bash is the old 3.2).
  • If a Bash script might be started as sh script.sh, add a guard that re-executes it:
Bash A guard that re-runs the script under Bash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The preamble must itself be valid POSIX (no [[ and no arrays before the exec), because the shell parses commands one at a time while executing, so the first exec line runs before the later Bash-only lines are parsed. That trick fails for syntax inside a compound command that already started, e.g. an array literal inside the same if block.

POSIX mode in Bash

bash --posix (or set -o posix, or running Bash under the name sh) switches Bash to POSIX-conforming behaviour for the places where it differs from the standard. This changes behaviour, not syntax: Bash in POSIX mode still accepts [[ and arrays, so it is not a test that your script is portable. Test with dash for that.

Bash What posix mode changes and what it does not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

POSIX mode is useful for making Bash behave like the standard when you run old scripts, and is what Bash does when it is invoked as sh. Treat it as a behaviour switch, not as a linter.

A mini bashism detector

Real tools for this are checkbashisms (from the devscripts package) and ShellCheck (below); neither is installed in the sandbox, so here is a small grep-based checker that shows the idea. It will miss things and report false positives, but it catches the most common mistakes in a #!/bin/sh script.

Bash A grep-based bashism finder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The last two lines show the authoritative check: dash -n script.sh parses without running and reports the first syntax error. It will only find syntax problems (the first one, then stops), while the grep rules find features dash would reject or silently mishandle. Together with ShellCheck, this is a good safety net.

ShellCheck

ShellCheck is the standard static analyser for shell scripts. It is not installed in the sandbox, so the following is read-only.

CONSOLE
$ shellcheck script.sh              # analyse using the shebang to pick the dialect
$ shellcheck -s sh script.sh        # force POSIX sh rules
$ shellcheck -s bash -S warning script.sh
TEXT
In script.sh line 3:
if [[ -z $name ]]; then
   ^-- SC3010 (warning): In POSIX sh, [[ ]] is undefined.

In script.sh line 12:
rm $file
   ^---^ SC2086 (info): Double quote to prevent globbing and word splitting.

Codes starting SC3 are portability findings for #!/bin/sh scripts; SC2086 (unquoted variable) is the most common finding in the wild. You can declare the dialect in the file with # shellcheck shell=sh, silence a justified exception with # shellcheck disable=SC2086, and run it in CI so that new bashisms cannot slip in.

GNU versus BSD tools

The other half of portability is the programs, not the shell. Linux uses GNU coreutils, sed, grep and friends; macOS and the BSDs ship their own, which have different options. The common problem spots:

Task GNU (Linux) BSD / macOS Portable approach
In-place edit sed -i 's/a/b/' f sed -i '' 's/a/b/' f write to a temp file, then mv
Extended regex in sed sed -E (also -r) sed -E use -E, not -r
Canonical path readlink -f p not available (older) cd "$(dirname "$p")" && pwd -P
File mode stat -c %a f stat -f %Lp f ls -ld, or detect the platform
Date from text date -d '2026-03-14' date -j -f ... see printf, Dates and Formatting
Perl regex grep -P not available grep -E
Skip empty input xargs -r default behaviour differs [ -s file ] && or find ... -exec ... +
Case-insensitive sort / sort -V supported partly avoid or test
mktemp mktemp -d mktemp -d -t prefix mktemp -d "${TMPDIR:-/tmp}/name.XXXXXX"
find extras -printf, -regextype not available -exec stat ... or -exec printf

We can't run BSD tools here, but we can show the habit that avoids the problem: detect, don't assume, and prefer a form that is the same everywhere.

Bash Portable in-place edit and feature detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

If your scripts are used mainly on one platform (your own servers, a Docker image), pick that platform's tools and state the requirement (# requires: GNU coreutils, bash >= 4.4) rather than uglifying the code. If they are shared tools for many machines, test them in a container for each target and run ShellCheck in CI.

zsh and other differences in brief

You will meet zsh mostly as macOS's interactive shell. Scripts for #!/bin/bash or #!/bin/sh are unaffected, but if you paste Bash scripts into zsh, three differences bite: zsh arrays are 1-indexed (Bash: 0-indexed); unquoted variables are not word-split by default (a feature in zsh, a bug source when moving code); and [[ =~ ]] stores captures in $match, not BASH_REMATCH. Our sandbox has no zsh, so this is read-only. A rule of thumb: write scripts for bash or sh explicitly, with a shebang, and use zsh only for interactive convenience.

So how portable should you be?

Situation Recommendation
Personal tools, CI jobs, server scripts for known Linux hosts Bash with #!/usr/bin/env bash; use [[ ]], arrays, set -euo pipefail. Don't apologise.
Container entrypoints on Alpine/BusyBox POSIX sh, or install bash in the image. Test with dash/busybox sh.
Installers, configure-style scripts, anything run on unknown systems POSIX sh and detect tools. Keep it short.
Scripts for macOS developers Bash 3.2 compatibility (no associative arrays, mapfile, ${x^^}, wait -n) or require Homebrew Bash.
Anything big and complicated Consider Python or Go instead: see Designing Maintainable Scripts.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. On Ubuntu, a script starts with #!/bin/sh and uses [[ -f $f ]]. It works when you run it as bash script.sh but fails when run as ./script.sh. Why?

    The shebang selects /bin/sh, which is dash on Debian and Ubuntu. [[ ]] is a Bash/ksh extension. Run as bash script.sh, the command you typed overrides the shebang.
  2. 2. Which line behaves differently, rather than failing, in dash?

    dash runs echo -e ... but prints a literal -e and always interprets backslashes. The other three are syntax errors. Silent differences are the dangerous kind, so use printf.
  3. 3. Does running a script with bash --posix prove that it is portable to dash?

    POSIX mode makes Bash follow the standard where the two differ, but it keeps its extensions. Test portability by running the script with dash (and dash -n for a syntax check).
  4. 4. What is the portable way to edit a file in place, given that GNU and BSD sed -i differ?

    BSD sed requires an argument after -i (even an empty one), GNU sed treats the next word as a suffix only when attached. Using a temp file avoids the option altogether.
  5. 5. What does the SC3010 family of ShellCheck messages report in a #!/bin/sh script?

    SC3xxx codes are portability checks for POSIX sh. SC2086 is the one about unquoted variables.

Summary

  • POSIX sh is the common denominator; dash (Debian/Ubuntu /bin/sh), BusyBox ash, Bash, ksh93 and zsh all differ beyond it. The shebang or the command you type decides which one runs a file.
  • Bashisms ([[ ]], arrays, <<<, <( ), (( )), ${x^^}, source, function, echo -e, {1..3}, pipefail) fail or, worse, behave differently in other shells. Use case, [ ] with =, printf, . file, and "$@" instead.
  • Test portability with dash script.sh and dash -n, with shellcheck -s sh, and with a bashism checker. bash --posix is a behaviour switch, not a test.
  • A POSIX preamble can re-exec the script under Bash; declare your requirements honestly.
  • GNU and BSD tools differ (sed -i, readlink -f, date -d, stat, grep -P): detect with command -v or feature tests, or use forms that are identical everywhere, like a temp file plus mv.
  • Choose portability by audience: Bash for known Linux hosts, POSIX sh for unknown systems and tiny containers, and a different language when the script outgrows the shell.

Next: Designing Maintainable Scripts