Everything so far has been Bash. But Bash is not always there. Ubuntu and Debian run /bin/sh scripts with dash, Alpine-based container images ship BusyBox ash, distroless images have no shell at all, and macOS still ships Bash 3.2 from 2007 (its default login shell is zsh). A script that works perfectly on your laptop can fail inside a Docker image or a CI runner. This lesson shows what "POSIX shell" means, which Bash features break elsewhere, and how to write scripts that run anywhere sh exists.
In simple words
- POSIX sh: the standard, basic shell language that works on every Unix system, including tiny containers.
- Bashism: a Bash-only feature that breaks in plain sh, such as [[ ]] or arrays.
- Portability: a script that runs the same on Ubuntu, Alpine, macOS and others.
What POSIX sh is
POSIX is a standard that defines a minimal shell language. Every Unix-like system has a shell at /bin/sh that implements it: dash, BusyBox ash, ksh, or Bash running in POSIX mode. If you write only POSIX features and use #!/bin/sh, your script runs on all of them.
Bash is a superset: it supports all of POSIX plus many extras ([[ ]], arrays, ${var//a/b}, <<<, process substitution, local …). Those extras are called bashisms.
| Where | What /bin/sh is |
|---|---|
| Ubuntu, Debian | dash (small and fast, strictly POSIX) |
| Alpine Linux, many container images | BusyBox ash |
| RHEL, Fedora, Amazon Linux | Bash in POSIX mode |
| macOS | Bash 3.2 in POSIX mode (zsh is the login shell) |
| distroless / scratch images | nothing |
The shebang decides
The first line is a promise about which language the file is written in:
#!/usr/bin/env bash— "this is a Bash script". Use any Bash feature. It needs Bash installed.#!/bin/sh— "this is a POSIX script". Use only POSIX features.
The bug is mixing them: Bash features under a #!/bin/sh shebang. On RHEL that works (sh is Bash), so nobody notices; on Ubuntu or Alpine it breaks.
Watch a bashism break
Create a script with a #!/bin/sh shebang that uses two Bash features:
printf '#!/bin/sh\nenv=${1:-prod}\nif [[ $env == prod ]]; then\n echo "production"\nfi\necho "done: ${env^^}"\n' > check.shchmod +x check.shcat check.sh./check.shbash check.sh#!/bin/shenv=${1:-prod}if [[ $env == prod ]]; then echo "production"fiecho "done: ${env^^}"./check.sh: 3: [[: not found./check.sh: 6: Bad substitutionproductiondone: PRODRun as sh (dash, because of the shebang), [[ is not a command, so the if is false and "production" is never printed; then ${env^^} is a "Bad substitution" that stops the script. Run with bash check.sh, the same file works, which is exactly why these bugs slip through.
Arrays are even worse: dash cannot parse them at all, so nothing in the script runs:
printf '#!/bin/sh\necho "starting"\nhosts=(web1 web2)\necho "${hosts[0]}"\n' > arr.shsh arr.sharr.sh: 3: Syntax error: "(" unexpectedLet ShellCheck find bashisms
ShellCheck reads the shebang. For a #!/bin/sh script it checks POSIX compatibility and reports every bashism (codes starting with SC3):
shellcheck check.shIn check.sh line 3:if [[ $env == prod ]]; then ^^ SC3010 (warning): In POSIX sh, [[ ]] is undefined.In check.sh line 6:echo "done: ${env^^}" ^^ SC3059 (warning): In POSIX sh, case modification is undefined....You can force a dialect with shellcheck -s sh script (or -s bash). Running ShellCheck in CI is the most reliable way to keep #!/bin/sh scripts portable.
Bashisms and their POSIX replacements
| Bash | POSIX sh |
|---|---|
[[ $a == $b ]] | [ "$a" = "$b" ] (quote everything) |
[[ $a == pre* ]] | case $a in pre*) … ;; esac |
[[ $s =~ ^[0-9]+$ ]] | case $s in *[!0-9]*|"") false ;; *) true ;; esac or grep -Eq |
[[ -f a && -r a ]] | [ -f a ] && [ -r a ] |
(( n > 5 )) | [ "$n" -gt 5 ] |
(( n++ )) | n=$((n + 1)) |
arr=(a b c) | set -- a b c (then "$@") or a space/newline separated string |
${var//a/b} | printf '%s' "$var" | sed 's/a/b/g' |
${var^^} | printf '%s' "$var" | tr '[:lower:]' '[:upper:]' |
${var:0:3} | printf '%s' "$var" | cut -c1-3 |
cmd <<< "$s" | printf '%s\n' "$s" | cmd |
<(cmd) | a temporary file from mktemp |
function f { } | f() { } |
source file | . file |
echo -e "a\tb" | printf 'a\tb\n' |
local x | not in POSIX (dash and ash support it anyway) |
$RANDOM, $SECONDS | awk 'BEGIN{srand(); print int(rand()*32768)}', date +%s |
read -p "Q? " x | printf 'Q? '; read -r x |
&> file | > file 2>&1 |
set -o pipefail | POSIX since 2024 and in recent dash; not in older shells |
What is POSIX and safe everywhere: $( ), $(( )) arithmetic, ${var:-default} and the other :-, :=, :?, :+ forms, ${var#pat}, ${var##pat}, ${var%pat}, ${var%%pat}, ${#var}, case, for, while, until, functions with name(), here-documents, set -eu, trap, getopts, [ ] and test, and printf.
The portable version
Here is check.sh rewritten in POSIX sh:
printf '#!/bin/sh\nset -eu\nenv=${1:-prod}\nif [ "$env" = prod ]; then\n echo "production"\nfi\nupper=$(printf %%s "$env" | tr "[:lower:]" "[:upper:]")\necho "done: $upper"\n' > check2.shchmod +x check2.sh./check2.shshellcheck check2.shecho "shellcheck exit code: $?"productiondone: PRODshellcheck exit code: 0[ ] is stricter than [[ ]]
[ is an ordinary command (test), so the shell expands and splits its arguments before [ sees them. That makes quoting mandatory:
name=""[ $name = admin ] # becomes: [ = admin ] → error: unary operator expected[ "$name" = admin ] # becomes: [ "" = admin ] → false, correctOther rules for [ ]:
- Use
=for strings, not==(dash rejects==). <and>are redirections inside[ ]; avoid string ordering, or escape them.- Combine tests with separate commands:
[ -f "$f" ] && [ -s "$f" ]. The old-aand-ooperators are deprecated.
Lists without arrays
POSIX sh has exactly one array: the positional parameters. set -- replaces them, and "$@" expands them safely:
set -- web1 web2 "db 1"echo "$# hosts"for h in "$@"; do echo "[$h]"; done3 hosts[web1][web2][db 1]Inside a function, set -- only affects that function's arguments. For simple lists of words without spaces, a plain string split by a for loop is also fine:
hosts="web1 web2 db1"for h in $hosts; do echo "$h"; done # intentionally unquoted, so it splitsTesting portability
- ShellCheck with the right shebang or
-s sh. - Run the script in the shells you target. Containers make this easy:
docker run --rm -v "$PWD":/s -w /s debian:12-slim sh ./check.sh # dashdocker run --rm -v "$PWD":/s -w /s alpine:3.20 sh ./check.sh # busybox ashdocker run --rm -v "$PWD":/s -w /s bash:3.2 bash ./check.sh # old macOS bashcheckbashisms(from Debian's devscripts package) is another linter specialised in this.- Locally,
dash script.shis a quick strict check if dash is installed.
When to choose which
Write POSIX sh when:
- the script runs inside container images you do not control (entrypoints, init containers, health checks), especially Alpine;
- it is an installer people pipe from the internet (
curl … | sh); - it is a Git hook or Makefile snippet that must work on every developer's machine.
Write Bash when:
- you control the environment (your servers, your CI images) and Bash is installed;
- the script benefits from arrays,
[[ ]],pipefail, process substitution and safer patterns.
Either way, make the shebang match the code.
Real-world scenario: the entrypoint that broke on Alpine
A team switched their API image from debian:bookworm to alpine to shrink it from 120 MB to 18 MB. The container crashed on start with:
/entrypoint.sh: line 9: syntax error: unexpected "("The entrypoint had a #!/bin/sh shebang but used an array, args=(--port "$PORT"). It had never failed before only because the Debian-based Dockerfile started it with CMD ["bash", "/entrypoint.sh"], so Bash ran it and the wrong shebang was ignored. The Alpine image had no Bash, so BusyBox ash ran it and could not parse the array.
The fix was to rewrite the five bashisms in POSIX form (ShellCheck flagged every one instantly) and add shellcheck to the image's CI pipeline. Installing Bash with apk add bash would also have worked, but it would have added size to every image just for a 30-line script.
Common mistakes
#!/bin/shwith Bash features, tested only withbash script.sh.==inside[ ]: works in Bash, fails in dash. Use=.- Unquoted variables in
[ ]: empty values cause "unary operator expected". echo -e/echo -n: behaviour differs between shells. Useprintf.- Assuming
/bin/bashexists: use#!/usr/bin/env bashfor Bash scripts, so they also work where Bash lives elsewhere (macOS with Homebrew, NixOS, BSD). - Writing Bash 5 features for macOS users: the built-in Bash 3.2 lacks associative arrays,
mapfileand${var,,}.
Practice
- Write a script with
#!/bin/shthat uses[[ ]], an array and<<<. Run it withshand withbash, and runshellcheckon it. - Rewrite it in POSIX sh until
shruns it correctly andshellcheckprints nothing. - Replace
[[ $file == *.log ]]with acasestatement. - Use
set --to loop over three hostnames, one of which contains a space. - Convert
echo -e "name\tvalue"toprintf.
Cheat sheet
#!/bin/sh POSIX only#!/usr/bin/env bash Bash features allowedshellcheck -s sh file check for bashisms (SC3xxx)[ "$a" = "$b" ] string compare (quote, single =)[ "$n" -gt 5 ] number compare[ -f "$f" ] && [ -r "$f" ] combine testscase $x in pre*) … ;; esac pattern matchset -- a b c; "$@" the only arrayn=$((n + 1)) arithmetic. ./lib.sh instead of sourceprintf '%s\n' "$x" | cmd instead of <<<printf 'a\tb\n' instead of echo -ex=$(printf %s "$s" | tr a-z A-Z) instead of ${s^^}Key takeaways
/bin/shis dash on Ubuntu/Debian and BusyBox ash on Alpine, not Bash.- The shebang must match the code: Bash features need
#!/usr/bin/env bash;#!/bin/shmeans POSIX only. - Arrays,
[[ ]],${var//},${var^^},<<<and<( )are bashisms; each has a POSIX replacement. - In
[ ], quote every variable and use=. - Let ShellCheck (SC3xxx warnings) and real shells in containers prove your script is portable.