sh Command Cheat Sheet
sh is the command name for the Bourne shell (or a compatible interpreter). It is the standard command language interpreter for Unix-like systems.
On Linux: /bin/sh is usually a symlink to bash (Red Hat) or dash (Debian/Ubuntu).
Synopsis
sh [options] [file]
Basic Usage
Run a Script
sh script.sh
sh, ignoring any logic that relies on bash specific extensions (like arrays [] or C-style loops (())).
Read from Stdin
sh -s < commands.txt
Inline Command (-c)
Execute a command string.
sh -c "echo Hello; date"
sh vs bash
sh aims for POSIX compliance. bash adds many non-standard features (Arrays, String manipulation, process substitution).
| Feature | sh (POSIX) |
bash |
|---|---|---|
| Arrays | No | Yes (arr=(a b)) |
| Brace Expansion | No | Yes ({1..10}) |
| Test | [ ] |
[[ ]] (Safer) |
| String Replace | sed needed |
${var/a/b} |
| Math | expr |
(( i++ )) |
| Here String | No | Yes (<<<) |
When to use sh?
- Portability: Script must run on any Unix (AIX, Solaris, BSD, Alpine Linux).
- Speed:
dash(Debian's sh) is much faster and lighter than bash (faster boot scripts). - Shebang:
#!/bin/shimplies simple, standard code.#!/bin/bashimplies features.
Debugging
See what the shell is doing.
-x: Print commands and arguments as they are executed.-n: Read commands but do not execute (syntax check).-e: Exit immediately if a command exits with a non-zero status.
# Debug a script
sh -x ./deploy.sh
Notes
- Symlink Check: Check what your system uses.
ls -l /bin/sh # lrwxrwxrwx 1 root root 4 /bin/sh -> bash