Bash-Specific Syntax vs. POSIX Shell Syntax
Bash is a superset of the POSIX shell language. Everything a POSIX sh script may contain also works in Bash, but Bash adds many features of its own: [[ ]], arrays, (( )), brace expansion, here strings, process substitution and more. A Bash feature used in a script that is meant for sh is called a bashism.
Lesson 188 explained when a script should be portable and how to test it. This lesson is the reference that goes with it: the Bash features that scripts use most, what happens to each one in a POSIX shell, and the POSIX way to get the same result. All POSIX examples were run under Dash 0.5.12, the /bin/sh of Ubuntu 24.04, and under Bash 5.2, with identical output.
How Bashisms Fail
Knowing how a bashism breaks is as important as knowing the replacement, because not all of them break loudly. When Dash meets Bash syntax, one of three things happens.
1. A syntax error. Some constructs cannot be parsed at all, and the script stops at that point:
$ dash -c 'diff <(echo a) <(echo b)'
dash: 1: Syntax error: "(" unexpected
$ dash -c 'tr a-z A-Z <<< hello'
dash: 1: Syntax error: redirection unexpected
2. A runtime error. The code parses, but a command or expansion is unknown:
$ dash -c 'x=abcdef; echo ${x:1:3}'
dash: 1: Bad substitution
$ dash -c 'mapfile -t lines < /dev/null'
dash: 1: mapfile: not found
$ dash -c '[ a == a ] && echo yes'
dash: 1: [: a: unexpected operator
The last one is worth remembering: == inside single brackets works in Bash, but POSIX test only knows =.
3. Silent wrong behavior. These are the dangerous ones, because nothing is reported and the script continues with wrong data:
$ dash -c 'echo hi > /tmp/f; x=$(< /tmp/f); echo "[$x]"'
[]
$ dash -c 'echo "[$RANDOM]"'
[]
$ dash -c 'echo {1..3}'
{1..3}
$ dash -c 'ls /nonexistent &> /dev/null; echo "after: $?"'
after: 0
ls: cannot access '/nonexistent': No such file or directory
$(< file)is a Bash shortcut for reading a file. In Dash it is a command substitution of an empty command with an input redirection, so the result is an empty string.$RANDOMis just an unset variable in Dash, which expands to nothing.{1..3}is not expanded, so a loop over it runs once with the literal text.&>is the most surprising. Dash readscmd &> fileascmd &(run in the background) followed by> file(create an empty file). The command's status is never checked,$?is 0, and its error message appears later, unredirected.
Because of this third group, "it ran without errors under sh" proves nothing. Read the output, run the tests, and use a checker such as ShellCheck (lesson 190).
Quick Reference
| Bash feature | Example | POSIX replacement |
|---|---|---|
[[ ]] conditional | [[ -f $f && $x == y ]] | [ -f "$f" ] && [ "$x" = y ] |
| Pattern match | [[ $f == *.log ]] | case $f in *.log) ... ;; esac |
| Regex match | [[ $v =~ ^v[0-9]+$ ]] | grep -Eq, expr, or case |
| Arithmetic command | (( n > 3 )), ((n++)) | [ "$n" -gt 3 ], n=$((n + 1)) |
| Arrays | a=(x y); "${a[@]}" | positional parameters: set -- x y; "$@" |
| Associative arrays | declare -A seen | a temporary file with grep/awk, or one awk program |
| Brace expansion | {1..5}, file.{txt,bak} | while loop with $(( )); write the list out |
| Substring | ${x:1:3} | cut -c2-4, expr substr, or awk |
| Replace in variable | ${x//a/b} | sed 's/a/b/g' |
| Case conversion | ${x^^}, ${x,,} | tr '[:lower:]' '[:upper:]' |
| Indirect expansion | ${!name} | eval "value=\${$name}" (only with validated names) |
| Is a variable set | [[ -v var ]] | [ -n "${var+set}" ] |
| ANSI-C quoting | $'a\tb' | printf 'a\tb' |
| Here string | cmd <<< "$x" | printf '%s\n' "$x" | cmd or a here document |
| Process substitution | diff <(a) <(b) | temporary files, or a pipe |
| Redirect both streams | cmd &> f, cmd |& next | cmd > f 2>&1, cmd 2>&1 | next |
| Read a file | $(< file) | $(cat file) |
function keyword | function f { ...; } | f() { ...; } |
source | source lib.sh | . ./lib.sh |
echo -e, echo -n | echo -e "a\tb" | printf 'a\tb\n' |
read options | read -p, -a, -s, -t | printf prompt, then read -r; stty -echo for hidden input |
mapfile, readarray | mapfile -t lines < f | while IFS= read -r line loop |
printf -v | printf -v x '%05d' "$n" | x=$(printf '%05d' "$n") |
select menu | select opt in ... | print a numbered list and read -r |
pipefail, shopt | set -o pipefail | explicit status checks (lesson 188) |
ERR, DEBUG, RETURN traps | trap handler ERR | EXIT and signal traps; check statuses explicitly |
| Special variables | $RANDOM, $SECONDS, $PIPESTATUS, $BASH_SOURCE | awk for random numbers, date +%s for time |
| Named file descriptors | exec {fd}> log | fixed numbers: exec 3> log |
The rest of this lesson explains the groups in this table with working examples.
Conditionals
[[ ]] is a Bash keyword, so the shell parses its contents specially: variables inside it are not word-split, && and || work inside the brackets, and == compares against a glob pattern. POSIX has only the test command, written [ ], which is an ordinary command with ordinary arguments. Three consequences follow:
- Quote every variable.
[ -f $file ]breaks when the name contains a space or is empty. - Use
=for string equality.==is a Bash extension oftest. - Combine conditions outside the brackets:
[ -f "$f" ] && [ -r "$f" ]. The-aand-ooperators oftestare marked obsolete because they can be ambiguous.
Pattern matching moves to case, which is POSIX, needs no external process and is often easier to read than a chain of tests:
version=v1.12.3
case $version in
v[0-9]*.[0-9]*.[0-9]*) echo "looks like a version" ;;
esac
For real regular expressions there is no shell syntax in POSIX; grep -E or expr do the matching. expr STRING : REGEX also extracts the part in