⚖️ POSIX vs. Non-POSIX
This is the most important distinction in shell scripting.
📜 What is POSIX?
Portable Operating System Interface. A set of standards that defines how a UNIX-like OS should behave.
- Goal: "Write once, run anywhere."
- Benefit: Your script runs on Linux, BSD, Solaris, macOS without changes.
- Cost: No fancy features (no arrays, no [[ ]], no {1..10}).
🎪 The "Bashisms" Trap
Bashisms are features specific to Bash that break in sh/dash.
| Feature | ❌ POSIX (sh) |
✅ Bash (bash) |
Why it matters |
|---|---|---|---|
| Conditionals | if [ "$a" = "$b" ]; then |
if [[ $a == $b ]]; then |
[[ ]] prevents word splitting bugs. |
| Arrays | ❌ Impossible | arr=(a b c) |
Critical for data structures. |
| Brace Expansion | ❌ Impossible | echo {1..10} |
Great for loops/filenames. |
| Process Substitution | ❌ Impossible | diff <(cmd1) <(cmd2) |
Powerful pipe alternative. |
| Functions | func() { } |
function func { } |
Syntax difference. |
🎯 The Golden Rule
If you use
#!/bin/sh, you are in a straightjacket. If you use#!/bin/bash, you are safe on 99% of Linux servers.
| Shebang | When to use? |
|---|---|
#!/bin/sh |
Init scripts, Docker Alpine, embedded systems. |
#!/bin/bash |
General automation, CI/CD, personal scripts. |
#!/usr/bin/env bash |
Preferred. Finds bash wherever it is installed. |