POSIX sh review: portable syntax and explicit failures

Identify Bash-only syntax in sh scripts, preserve quoted arguments and review portable failure handling with examples and explicit compatibility limits.

A file invoked with sh is not guaranteed to be Bash, even if it worked in an interactive Bash terminal. Review the chosen interpreter and the oldest implementation you must support. Portable shell code is a compatibility decision, not an automatic improvement: a script that genuinely needs Bash arrays can declare Bash instead of disguising them behind a sh shebang.

Separate shell selection from syntax

The shebang is evidence of intended invocation on systems that honor it, but sh file overrides that choice. [[ conditions, Bash arrays, here-strings and the function keyword are not generally supported by traditional sh implementations such as dash. Prefer [ "$a" = "$b" ], case patterns and name() { ...; } when that compatibility is required. Check the complete construct rather than replacing tokens mechanically; a Bash regex test has no direct portable single-bracket equivalent.

Define the compatibility baseline

POSIX evolves, and existing installed shells do not implement every recent edition. POSIX.1-2024 includes dollar-single-quote syntax and pipefail, while older specifications and many deployed shells do not. The instant portability rules conservatively flag these as compatibility questions. Describe your target shell and version when interpreting a warning. Do not claim a construct is universally impossible simply because an older dash installation rejects it.

Preserve words and input

Use quoted scalar expansions in ordinary commands and "$@" to forward positional arguments individually. Positional parameters can represent an argument list where Bash arrays are unavailable. printf is preferable when output requires predictable escape handling, because echo option and escape behavior differs across implementations. For line input, IFS= read -r line preserves leading whitespace and backslashes; consider how the last line without a newline should be handled if the application requires it.

Handle critical errors without assuming pipefail

For a broad traditional sh baseline, check critical steps separately instead of copying set -euo pipefail from a Bash tutorial. set -eu is supported widely, but optional variables and expected nonzero statuses need deliberate handling. Split a download from subsequent processing, guard cd and avoid relying on the final pipeline command to report all failures. Portability also includes external utilities: GNU-specific sed or find options are not made portable by changing the shell syntax.

Review example

This example intentionally combines a sh shebang with array and conditional syntax that requires a different compatibility baseline. Choose a declared Bash interpreter or a genuine portable rewrite.

#!/bin/sh
items=(one two)
if [[ "$1" == ready ]]; then
  printf "%s\n" "${items[0]}"
fi
Open the checker

What cannot be verified

Text review cannot establish which executable a target machine assigns to /bin/sh or whether its utilities implement the expected extensions. Confirm those deployment facts separately. Compatibility findings should identify the construct and target assumption, not invent a ShellCheck rule number or treat every extension as a security flaw. The references below explain each detected topic.

Finding references

rm -rf with a variable path

Recursive/forced rm using a variable path. If the variable is empty or unset, this can delete far more than intended.

Suggested safeguard: Guard the path: use "${dir:?dir is required}" and quote the expansion, e.g. rm -rf "${dir:?}/subdir".

SC2115

Piping a download into a shell

Remote content is piped straight into a shell. A compromised or partially downloaded response executes with your privileges.

Suggested safeguard: Download to a file, verify it (checksum or signature), inspect it, then execute it as a separate step.

eval with an expansion

eval is used with an expansion. Any attacker-controlled part of that string becomes executable code.

Suggested safeguard: Replace eval with an array, a case statement, or indirect expansion (${!name}) — none of which re-parse data as code.

SC2294

World-writable chmod 777

chmod 777 makes the target world-writable, so any local account can modify or replace it.

Suggested safeguard: Grant the narrowest mode that works — 755 for executables, 644 for data, 700 for private state.

cd without a failure guard

cd without a failure guard. If the directory does not exist the script keeps running in the wrong working directory.

Suggested safeguard: Write cd "$dir" || exit 1 (or set -e plus a quoted path) so the script stops instead of operating on the wrong tree.

SC2164

Unquoted variable expansion

Unquoted variable expansion. Values containing spaces or glob characters get word-split and globbed before the command sees them.

Suggested safeguard: Wrap the expansion in double quotes: "$var" / "${arr[@]}".

SC2086

Legacy backtick substitution

Legacy backtick command substitution. It nests badly and handles backslashes differently from the modern form.

Suggested safeguard: Use $(command) instead of `command`.

SC2006

Non-portable echo -e

echo -e is not portable — it is undefined in POSIX sh and behaves differently across shells and /bin/echo builds.

Suggested safeguard: Use printf '%b\n' "$value" for escape handling that behaves the same everywhere.

SC3037

sudo inside a script

The script invokes sudo. It will either prompt interactively in the middle of a run or silently require passwordless sudo.

Suggested safeguard: Check privileges up front (if [[ $EUID -ne 0 ]]) and fail with a clear message, rather than escalating mid-script.

Predictable /tmp path

Fixed path under /tmp. Predictable temp paths are a symlink-attack vector on shared machines and collide between concurrent runs.

Suggested safeguard: Create the file with mktemp (or mktemp -d) and remove it in a trap.

SC2129

Parsing ls output

Parsing the output of ls. Filenames containing spaces or newlines break the pipeline.

Suggested safeguard: Use a glob or find -print0 with a while IFS= read -r -d '' loop.

SC2012

read without -r

read without -r mangles backslashes in the input.

Suggested safeguard: Use read -r (and IFS= read -r line when preserving leading whitespace).

SC2162

[[ ]] in a POSIX sh script

[[ ]] is a Bash/Zsh keyword. dash, ash and BusyBox sh report "[[: not found".

Suggested safeguard: Use [ ... ] with quoted operands, or switch the shebang to bash.

Arrays in a POSIX sh script

POSIX sh has no arrays; this line is a syntax error in dash.

Suggested safeguard: Use positional parameters (set -- a b c) or a newline-separated string.

function keyword in POSIX sh

The function keyword is not POSIX.

Suggested safeguard: Define functions as name() { ...; }.

== inside [ ] in POSIX sh

== inside [ ] is a Bash extension; POSIX test only knows =.

Suggested safeguard: Use a single = for string comparison.

source in POSIX sh

source is a Bash builtin; POSIX sh uses the dot command.

Suggested safeguard: Replace source file with . ./file.

Here-string in POSIX sh

Here-strings (<<<) are not POSIX.

Suggested safeguard: Use printf '%s\n' "$var" | cmd or a here-document.

$'...' quoting in POSIX sh

ANSI-C quoting $'...' is not supported by every POSIX sh.

Suggested safeguard: Build the string with printf instead.

Missing shebang

No shebang on the first line, so the interpreter depends on how the file is invoked.

Suggested safeguard: Add #!/usr/bin/env bash, #!/bin/sh or #!/usr/bin/env zsh as the first line.

SC2148

/bin/sh shebang with Bash syntax

The shebang says /bin/sh but the script uses Bash-only syntax, which fails where /bin/sh is dash.

Suggested safeguard: Change the shebang to bash or rewrite the constructs in POSIX form.

Missing strict mode

Without set -e, -u (and pipefail in Bash/Zsh) the script continues after failed commands.

Suggested safeguard: Add set -euo pipefail (set -eu in POSIX sh) near the top.

Unbalanced if/fi

The number of if and fi keywords differs, which is a syntax error.

Suggested safeguard: Close every if with a matching fi.

Unbalanced do/done

The number of do and done keywords differs, which is a syntax error.

Suggested safeguard: Close every for/while/until body with done.

Official references