Portable Shell Scripts: 7 Easy Rules to Avoid Errors
Portable shell scripts are scripts that give the same result in every shell that may run them, not only in the Bash you wrote them in. The old version of this article listed general advice such as "use POSIX syntax" and "avoid system-specific tools" without showing a single failure. This rewrite runs the old snippets and 20 common Bash habits in six shells on Debian 13: dash (which is /bin/sh there), Bash 5.2.37, Bash in --posix mode, BusyBox sh, mksh R59 and posh, a shell that accepts only strict POSIX. ShellCheck then flags the same problems automatically.
Contents
What /bin/sh is: why portable shell scripts break
The shebang #!/bin/sh does not mean Bash. In the lab container ls -l /bin/sh shows /bin/sh -> dash; the target of that link differs between distributions. A script that works on your laptop because sh is Bash can fail on a server where it is dash, and this is the main reason why portable shell scripts need tests. The rule set for the shell language is the POSIX Shell Command Language. Anything outside it is a bashism: it may work, but you must not rely on it.
The old examples: which ones were really portable shell scripts?
All the examples of the original post were run by the six shells. The file test [ -e "$1" ], the loop for file in "$1"/* with [ -f "$file" ], and the default value : "${MY_VAR:=default_value}" gave identical output everywhere, including a file name with a space (Found file: d/b c.txt). The -f test matters: on an empty directory the loop with the test printed nothing, and without it every shell printed the literal pattern Found file: empty/*.
The fourth example is the weak one. It used command=$(which curl). It ran in all six shells, but which is not a shell built-in or a POSIX utility, so its presence and its messages depend on the system. Use the built-in instead:
if command -v curl >/dev/null 2>&1; then
echo "curl found at $(command -v curl)"
else
echo "curl not found"
fi
In the test, command -v curl printed nothing and returned a non-zero code (127 in dash) when curl was missing, and command -v sh printed /usr/bin/sh in all six shells. Check the exit code, not the text, because the output format of which differs between systems.
Bash features that fail in portable shell scripts
Each line below was saved as its own one-line script and run by every shell. The figure shows a sample; the full list is in the table.
![Portable shell scripts test: [[ ]], arrays, echo -e, brace expansion and source fail in dash, posh and BusyBox](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCAi45kw4oz-htn2JHiQNBebvrZIdhxoiSfThf-_uwxaWZk5LmP21CdH7JBrJAm80wkGu5n-HmZsMJ8zGJrNZbydFNq3ewVDxV1_WjXS4-KthDN3i27d_wLdiVepD2DntK4v1GkkoGYNMva8-etUUEG8KT063di8MYo-0GknlB-3YYQT1eJtFXCiGbq1cB/s1600-rw/image.png)
| Feature | Result in the lab | POSIX replacement |
|---|---|---|
[[ abc == a* ]] | "[[: not found" in dash and posh | case abc in a*) ... ;; esac |
[ a == a ] | "unexpected operator" in dash and posh | [ a = a ] |
a=(1 2 3) | syntax error in dash, BusyBox and posh | positional parameters: set -- 1 2 3 |
function f { ...; } | syntax error in dash and posh | f() { ...; } |
cat <<< hello | syntax error in dash, BusyBox and posh | printf '%s\n' hello | cat |
echo -e "a\tb" | dash and posh print -e a then a tab | printf 'a\tb\n' |
source ./f | "source: not found" in dash and posh | . ./f |
echo {1..3} | unchanged {1..3} in dash, BusyBox, mksh and posh | seq 1 3 or a while loop |
${s:1:3}, ${s//-/+} | "Bad substitution" in dash and posh | cut, sed or case |
$RANDOM | empty in dash and posh | awk 'BEGIN{srand(); print rand()}' |
set -o pipefail | "bad option" in posh only | check each step, or use Bash on purpose |
cat <(echo hi) | syntax error in dash, mksh and posh | a temporary file or a pipe |
One result is easy to miss. The first is echo "a\tb" printed a literal backslash-t in Bash and BusyBox, but a tab in dash, mksh and posh; echo with escapes is a trap that printf removes. The features that worked in all six shells in the test were local, $(( 2+3 )) and the dot command. local is not in POSIX, but every shell tested accepted it.
Let ShellCheck find the problems in portable shell scripts
You do not need six shells for every change. Run shellcheck -s sh script.sh, which checks against POSIX sh rules. On a test file with [[ ]], echo -e and an array, it reported SC3010: In POSIX sh, [[ ]] is undefined, SC3037: In POSIX sh, echo flags are undefined and SC3030: In POSIX sh, arrays are undefined, and exited with code 1. The old file test, loop and default-value examples exited with 0. It also exited with 0 on the which curl example, so ShellCheck does not replace the lesson above.
Each code has a page in the ShellCheck wiki. For checks inside your own tools, a related post, the Bash caller command, shows a Bash-only debugging feature that you should keep out of #!/bin/sh scripts.
A short checklist for portable shell scripts
- Pick the interpreter on purpose:
#!/bin/shfor POSIX,#!/usr/bin/env bashwhen you need Bash features. - Test your portable shell scripts with dash and BusyBox sh, plus Bash, and run
shellcheck -s shin your editor or CI. - Replace
whichwithcommand -v,echo -ewithprintf,sourcewith the dot command,==with=. - Quote every variable and guard glob loops with
[ -f "$file" ]. - Keep arrays,
[[ ]]and string slicing out of scripts that must run on a minimal image.
The article on Bash script examples covers the Bash side; use it when portability is not a requirement. Not tested here: BSD and macOS tools such as the sed -i argument, which differ from GNU; GNU sed and BusyBox sed both accepted sed -i 's/a/X/' in the lab.
FAQ
Are portable shell scripts harder to write? They are a little longer, because you lose arrays and string slicing. In return, the same file runs on dash, BusyBox and Bash.
Is Bash --posix mode a good portability test? No. In the test it still accepted [[ ]], arrays and function, so only a different shell such as dash or posh shows the failures.
Comments
Post a Comment