Bash-Specific Syntax vs. POSIX Shell Syntax

Su Suriya Ravichandran Updated 06 Dec 2026
15 min read ·Lesson 189 of 205

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.
  • $RANDOM is 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 reads cmd &> file as cmd & (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 featureExamplePOSIX 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))
Arraysa=(x y); "${a[@]}"positional parameters: set -- x y; "$@"
Associative arraysdeclare -A seena 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 stringcmd <<< "$x"printf '%s\n' "$x" | cmd or a here document
Process substitutiondiff <(a) <(b)temporary files, or a pipe
Redirect both streamscmd &> f, cmd |& nextcmd > f 2>&1, cmd 2>&1 | next
Read a file$(< file)$(cat file)
function keywordfunction f { ...; }f() { ...; }
sourcesource lib.sh. ./lib.sh
echo -e, echo -necho -e "a\tb"printf 'a\tb\n'
read optionsread -p, -a, -s, -tprintf prompt, then read -r; stty -echo for hidden input
mapfile, readarraymapfile -t lines < fwhile IFS= read -r line loop
printf -vprintf -v x '%05d' "$n"x=$(printf '%05d' "$n")
select menuselect opt in ...print a numbered list and read -r
pipefail, shoptset -o pipefailexplicit status checks (lesson 188)
ERR, DEBUG, RETURN trapstrap handler ERREXIT and signal traps; check statuses explicitly
Special variables$RANDOM, $SECONDS, $PIPESTATUS, $BASH_SOURCEawk for random numbers, date +%s for time
Named file descriptorsexec {fd}> logfixed 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 of test.
  • Combine conditions outside the brackets: [ -f "$f" ] && [ -r "$f" ]. The -a and -o operators of test are 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 0 1, which replaces BASH_REMATCH:

if printf '%s\n' "$version" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then
  echo "valid version"
fi
major=$(expr "$version" : 'v\([0-9]*\)\.')
echo "major=$major"
looks like a version
valid version
major=1

expr regular expressions are always anchored at the start of the string and use the basic regex syntax, so groups are written 0 1.

Arithmetic

Arithmetic expansion $(( )) is POSIX; the arithmetic command (( )) and let are not. Comparisons therefore use test:

count=$((count + 1))              # instead of ((count++))
total=$((size * 1024))
if [ "$count" -gt 3 ]; then       # instead of (( count > 3 ))
  echo "more than three"
fi

Assignment operators such as $((x += 1)) are POSIX, but the increment operators ++ and -- are not required by the standard, and Dash rejects them:

$ dash -c 'x=5; : $((x+=1)); echo $x'
6
$ dash -c 'x=5; echo $((x++))'
dash: 1: arithmetic expression: expecting primary: "x++"

Writing ((x++)) as a command is worse: Dash parses it as two nested subshells running a command named x++, prints "not found" and leaves x unchanged (lesson 188).

Arrays and Associative Arrays

POSIX sh has no arrays. It has exactly one list that preserves elements containing spaces: the positional parameters. set -- assigns them, $# counts them, "$@" expands to all of them, and for item do loops over them:

set -- one "two words" three
echo "count=$# second=$2"
for item do printf '<%s>\n' "$item"; done
eval "last=\${$#}"; echo "last=$last"
count=3 second=two words
<one>
<two words>
<three>
last=three

The eval line reads the last parameter; it is safe here because $# is always a number. When a script needs more than one list, or random access by key, the POSIX answer is to leave the shell: store items one per line in a temporary file, or move the whole data processing into awk, which has associative arrays built in. The conversion example later in this lesson does exactly that.

Parameter Expansion

POSIX defines a useful core of parameter expansions, and all of these work in Dash:

ExpansionMeaning
${#x}length of the value
${x#pat}, ${x##pat}remove the shortest or longest match of pat from the start
${x%pat}, ${x%%pat}remove the shortest or longest match from the end
${x:-word}, ${x:=word}default value, with or without assigning it
${x:?message}stop with an error if unset or empty
${x:+word}word if set and non-empty, otherwise nothing
${x+word}word if set at all, even if empty
$ dash -c 'x=abc; echo "${#x} ${x#a} ${x%c}"'
3 bc ab

The Bash additions, substrings ${x:1:3}, replacement ${x//a/b}, case conversion ${x^^} and indirection ${!x}, all fail with "Bad substitution". Their replacements are small external commands:

x=abcdef
printf '%s\n' "$x" | cut -c2-4                      # bcd        (${x:1:3})
name=report.tar.gz
printf '%s\n' "$name" | tr '[:lower:]' '[:upper:]'  # REPORT.TAR.GZ (${name^^})
path=/var/log/app/error.log
printf '%s\n' "$path" | sed 's|/|:|g'               # :var:log:app:error.log (${path//\//:})

Note that cut -c2-4 counts from 1 while ${x:1:3} counts from 0. To check whether a variable is set, which Bash does with [[ -v var ]], use the + expansion:

unset v
[ -n "${v+set}" ] || echo "v is unset"

Quoting and Strings

$'...' (ANSI-C quoting) turns escape sequences such as \t and \n into the actual characters. Dash does not know it and keeps the dollar sign and backslashes:

$ dash -c "printf '%s' \$'a\\tb'; echo"
$a\tb

The portable way to produce special characters is printf, whose escapes are standardized. A newline can also be stored by writing it literally inside quotes:

tab=$(printf '\t')
nl='
'
printf '[%s]\n' "a${tab}b"

echo -e and echo -n belong here too: POSIX leaves echo's handling of options and backslashes implementation-defined, so printf is the only reliable choice (lesson 188).

Redirection and Substitution

Here strings (<<<) feed a string to a command's standard input. A pipe from printf or a here document does the same in POSIX:

printf '%s\n' hello | tr 'a-z' 'A-Z'
tr 'a-z' 'A-Z' <<EOT
hello
EOT

One difference matters: commands on the right side of a pipe may run in a subshell, so printf '%s\n' "$x" | read -r a b does not set a and b in the current shell. A here document does not create a subshell, so use it with read.

Process substitution (<(cmd)) gives a command's output a file name. POSIX scripts write the output to temporary files instead:

a=$(mktemp); b=$(mktemp)
printf 'x\ny\n' > "$a"
printf 'x\nz\n' > "$b"
diff "$a" "$b"
rm -f "$a" "$b"

&> and |& redirect both output streams. Spell them out as > file 2>&1 and 2>&1 |. The order matters: 2>&1 must come after the redirection of standard output (lesson 60).

$(< file) becomes $(cat file).

Commands and Built-ins

  • Functions are defined as name() { ...; }. The function keyword is a syntax error in Dash.
  • source becomes .. POSIX . searches PATH for names without a slash, so write . ./lib.sh or use a full path.
  • local is not in POSIX, but Dash, BusyBox ash, Bash and zsh all implement it; declare and typeset have no POSIX equivalent.
  • read in POSIX supports only -r. Print a prompt with printf 'Name: ' before read -r name; read a list by looping with while IFS= read -r line; hide a password with stty -echo before and stty echo after reading.
  • mapfile and readarray become a while read loop.
  • printf -v var becomes var=$(printf ...). Command substitution removes trailing newlines, which is usually what is wanted.
  • select has no POSIX counterpart; print a numbered list with printf and read the choice with read -r, then validate it with case (lesson 134).

Shell Options, Traps and Special Variables

shopt is Bash-only, and of the set -o options, pipefail is only standardized since 2024 and missing in Dash 0.5.12. Lesson 188 shows how to check the status of the left side of a pipeline without it.

trap is POSIX, but only for EXIT and real signals. Bash's pseudo-signals ERR, DEBUG and RETURN do not exist; Dash rejects them with trap: ERR: bad trap. Signal names are written without SIG.

Bash's special variables have no POSIX equivalent and are simply empty in Dash: $RANDOM, $SECONDS, $EPOCHSECONDS, $PIPESTATUS, $BASH_SOURCE, $FUNCNAME. Even $LINENO, which POSIX does define, is empty in Dash 0.5.12. Typical replacements:

start=$(date +%s)                     # instead of $SECONDS
awk 'BEGIN { srand(); print int(rand() * 32768) }'   # instead of $RANDOM

In most awk implementations srand() seeds from the current time in seconds, so two calls within the same second can return the same number; read from /dev/urandom with od when better randomness is needed.

A Complete Conversion

The following Bash script turns article titles into URL slugs and reports titles that would produce the same slug. It uses a typical set of Bash features: mapfile, an associative array, ${x,,}, ${x//pat/rep}, [[ =~ ]], (( )) and pipefail:

#!/usr/bin/env bash
# slugs.bash - turn article titles into URL slugs and report duplicates (Bash version)
set -euo pipefail

declare -A first_line=()          # slug -> line where it first appeared
dupes=0
mapfile -t titles < "${1:-/dev/stdin}"

for i in "${!titles[@]}"; do
  title=${titles[i]}
  [[ $title =~ ^[[:space:]]*$ ]] && continue            # skip blank lines
  slug=${title,,}                                       # lowercase
  slug=${slug//[^a-z0-9]/-}                             # anything else becomes -
  while [[ $slug == *--* ]]; do slug=${slug//--/-}; done
  slug=${slug#-} slug=${slug%-}                         # trim dashes at both ends
  if [[ -n ${first_line[$slug]:-} ]]; then
    printf 'DUPLICATE %s (line %d, first seen on line %d)\n' \
      "$slug" "$((i + 1))" "${first_line[$slug]}" >&2
    ((++dupes))
  else
    first_line[$slug]=$((i + 1))
    printf '%s\n' "$slug"
  fi
done
(( dupes == 0 ))

(((++dupes)) uses the pre-increment on purpose: ((dupes++)) evaluates to the old value 0, which counts as failure and would stop the script under set -e.)

The POSIX version replaces each feature with its counterpart from the reference table:

#!/bin/sh
# slugs.sh - turn article titles into URL slugs and report duplicates (POSIX version)
set -eu

seen=$(mktemp)                    # one "slug line-number" pair per line
trap 'rm -f "$seen"' EXIT
dupes=0
n=0

while IFS= read -r title || [ -n "$title" ]; do
  n=$((n + 1))
  case $title in
    *[![:space:]]*) ;;                                  # has visible text
    *) continue ;;                                      # skip blank lines
  esac
  slug=$(printf '%s\n' "$title" | tr '[:upper:]' '[:lower:]' |
         sed 's/[^a-z0-9][^a-z0-9]*/-/g; s/^-//; s/-$//')
  first=$(awk -v s="$slug" '$1 == s { print $2; exit }' "$seen")
  if [ -n "$first" ]; then
    printf 'DUPLICATE %s (line %d, first seen on line %d)\n' \
      "$slug" "$n" "$first" >&2
    dupes=$((dupes + 1))
  else
    printf '%s %d\n' "$slug" "$n" >> "$seen"
    printf '%s\n' "$slug"
  fi
done < "${1:-/dev/stdin}"

[ "$dupes" -eq 0 ]

What Changed and Why

Bash versionPOSIX versionNote
mapfile -t titles + index loopwhile IFS= read -r title with a counter n|| [ -n "$title" ] also processes a last line without a newline, which mapfile handles automatically
[[ $title =~ ^[[:space:]]*$ ]]case with *[![:space:]]*"contains at least one non-space character" is the same test turned around
${title,,}tr '[:upper:]' '[:lower:]'
${slug//[^a-z0-9]/-} + loop squeezing --one sed command[^a-z0-9][^a-z0-9]* matches a whole run of other characters, so no squeezing loop is needed
declare -A first_linea temporary file searched with awkremoved by the EXIT trap
((++dupes)), (( dupes == 0 ))$(( )) and [ -eq ]
set -o pipefailnot neededthe only pipeline feeds tr and sed, which do not fail on text input

Comparing the Two Versions

The test input contains mixed case, punctuation, a blank line, a duplicate written differently, and a last line without a trailing newline:

Writing Portable Shell Scripts
  Bash vs. POSIX: What Changes?

Using ShellCheck (in CI!)
writing portable shell-scripts
C++ & Rust -- A Comparison
Last Line Without Newline

Both versions produce exactly the same standard output, the same message on standard error and the same exit status:

$ bash slugs.bash titles.txt; echo "status $?"
writing-portable-shell-scripts
bash-vs-posix-what-changes
using-shellcheck-in-ci
c-rust-a-comparison
last-line-without-newline
DUPLICATE writing-portable-shell-scripts (line 5, first seen on line 1)
status 1
$ dash slugs.sh titles.txt; echo "status $?"
writing-portable-shell-scripts
bash-vs-posix-what-changes
using-shellcheck-in-ci
c-rust-a-comparison
last-line-without-newline
DUPLICATE writing-portable-shell-scripts (line 5, first seen on line 1)
status 1

Comparing the saved outputs with cmp confirmed that they are byte-for-byte identical, and the POSIX version also gives the same result when run by Bash. The Bash version, run with Dash, fails on its third line: set: Illegal option -o pipefail.

Two limitations of the comparison are worth knowing. With non-ASCII titles the versions can differ, because ${x,,} and tr handle multibyte characters differently depending on the locale. And the POSIX version starts several processes per line (tr, sed, awk), so it is much slower on large inputs. For thousands of titles, the natural POSIX solution is a single awk program that does the lowercasing, replacement and duplicate tracking for the whole file; lesson 191 explains why that difference matters.

Choosing Between Bash and POSIX

Converting to POSIX has a cost: arrays, [[ ]], mapfile and the extended parameter expansions make scripts shorter and safer, and their replacements are often longer or slower. A sensible rule is to write Bash, with a bash shebang, whenever Bash is guaranteed to exist, and to write POSIX sh when the script must run where Bash may be missing, such as Alpine containers, minimal images and installers. The mistake to avoid is the mixture: Bash features behind a #!/bin/sh line.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Bash-Specific Syntax vs. POSIX Shell Syntax and get answers drawn from it.

Signed-in readers only.