Bash 5.3 Reference
Overview
Complete reference for GNU Bash 5.3 (May 2025). Covers all shell syntax, builtins, variables, expansions, redirections, and features. Use this skill whenever writing or reviewing bash scripts to ensure correctness.
This file is a scannable hub. Each section below summarizes key constructs with compact tables. Use the Read tool to load referenced files identified as relevant for full syntax, edge cases, and examples:
- Syntax & commands (quoting, compound commands, pipelines):
shell-syntax-and-commands.md
- Functions, parameters & expansions (all expansion types, pattern matching):
functions-parameters-expansions.md
- Redirections & execution (I/O, here docs, FDs, command search, signals):
redirections-and-execution.md
- Builtins (
set, shopt, declare, read, printf, trap, etc.): shell-builtins.md
- Variables (
BASH_REMATCH, PIPESTATUS, EPOCHSECONDS, etc.): shell-variables.md
- Bash features (startup files, arrays, arithmetic, POSIX mode, conditionals):
bash-features.md
- Job control, readline & history (bg/fg, completion, history expansion):
job-control-readline-history.md
When to Use
- Need exact syntax for any Bash construct (loops, conditionals, expansions, redirections)
- Writing, reviewing, or debugging Bash scripts
- Unsure about quoting rules, expansion order, or operator behavior
- Need to look up a specific builtin, variable, shopt option, or test operator
- Verifying Bash 5.3-specific features (
${ command; }, GLOBSORT, BASH_MONOSECONDS)
When NOT to Use
- Writing POSIX-portable
sh scripts (this covers Bash-specific features beyond POSIX)
- Zsh, Fish, or other shell syntax
- Structuring multi-file Bash projects (use
bitranox:coding-bash-clean-architecture instead)
Before you reach for Bash (and before you ship)
- Prefer a Python script over shell for any real logic (global working rule). Shell has sharp edges
that bite repeatedly - a leading-dash path makes
dirname/grep treat it as an option, sed -i
can double-apply, and cmd | head reports head's exit status not cmd's. For path handling, text
transforms, or multi-step automation, write a Python (stdlib) script. Reserve Bash for a simple
one-shot command invocation (including launching a Python script).
- Gate every Bash script you DO ship with
shellcheck and bash -n before committing - required
checks, not optional. shellcheck -x script.sh (follows sourced files) catches quoting,
word-splitting, and unset-variable bugs; bash -n script.sh catches syntax errors without executing
it. Add shfmt -i 4 -d script.sh where the project formats shell.
Reference Files
| File |
Contents |
shell-syntax-and-commands.md |
Quoting, comments, reserved words, pipelines, lists, compound commands (if/for/while/case/select/[[/(( ), grouping, coprocesses |
functions-parameters-expansions.md |
Shell functions, positional/special parameters, ALL expansion types (brace, tilde, parameter, command substitution, arithmetic, process substitution, word splitting, globbing, pattern matching) |
redirections-and-execution.md |
All redirection types, here docs/strings, file descriptors, command search/execution, execution environment, exit status, signals, shell scripts |
shell-builtins.md |
All Bourne shell builtins, all Bash builtins, set options, shopt options, special builtins |
shell-variables.md |
All Bourne shell variables, all Bash variables (BASH_*, COMP_*, HIST*, READLINE_*, etc.) |
bash-features.md |
Invocation options, startup files, interactive shell behavior, conditional expressions, arithmetic, aliases, arrays, directory stack, prompt control, restricted shell, POSIX mode, compatibility mode |
job-control-readline-history.md |
Job control (bg/fg/jobs/disown), readline configuration, all bindable commands, vi mode, programmable completion (complete/compgen/compopt), history expansion |
Which File Do I Need?
| I need to... |
Read |
| Write a function, use parameters/expansions, do string manipulation |
functions-parameters-expansions.md |
Use if/for/while/case/select/[[ ]]/(( )), or understand quoting |
shell-syntax-and-commands.md |
| Redirect I/O, use here docs/strings, understand fd management |
redirections-and-execution.md |
Look up a builtin (set, shopt, declare, read, printf, trap, etc.) |
shell-builtins.md |
Check a shell variable (BASH_REMATCH, PIPESTATUS, EPOCHSECONDS, etc.) |
shell-variables.md |
| Understand startup files, arrays, arithmetic, POSIX mode, or conditional expressions |
bash-features.md |
| Work with job control, readline, completion, or history expansion |
job-control-readline-history.md |
Quick Reference: Most-Used Constructs
Quoting
Full details: shell-syntax-and-commands.md (section 3.1.2, Quoting)
| Syntax |
Behavior |
\x |
Escape single character |
'text' |
Literal string, no expansion |
"text" |
Allows $, `, \, ! expansion |
$'text' |
ANSI-C escapes: \n, \t, \e, \xHH, \uHHHH, \UHHHHHHHH |
$"text" |
Locale-specific translation |
Parameter Expansion
Full details: functions-parameters-expansions.md (section 3.5.3)
| Syntax |
Result |
${var:-default} |
Use default if var unset/null |
${var:=default} |
Assign default if var unset/null |
${var:+alternate} |
Use alternate if var IS set |
${var:?error} |
Error if var unset/null |
${#var} |
String length |
${var:offset:length} |
Substring |
${var#pattern} |
Remove shortest prefix match |
${var##pattern} |
Remove longest prefix match |
${var%pattern} |
Remove shortest suffix match |
${var%%pattern} |
Remove longest suffix match |
${var/pat/str} |
Replace first match |
${var//pat/str} |
Replace all matches |
${var/#pat/str} |
Replace if matches beginning |
${var/%pat/str} |
Replace if matches end |
${var^pattern} |
Uppercase first char |
${var^^pattern} |
Uppercase all chars |
${var,pattern} |
Lowercase first char |
${var,,pattern} |
Lowercase all chars |
${!prefix*} |
Names matching prefix |
${!name[@]} |
Array indices/keys |
${!var} |
Indirect expansion |
${var@Q} |
Quote for reuse |
${var@E} |
Expand escape sequences |
${var@P} |
Expand as prompt string |
${var@A} |
Assignment statement form |
${var@a} |
Attribute flags |
${var@U} |
Uppercase all |
${var@u} |
Uppercase first |
${var@L} |
Lowercase all |
${var@K} |
Key-value pairs (assoc arrays) |
Special Parameters
Full details: functions-parameters-expansions.md (section 3.4.2, Special Parameters)
| Param |
Meaning |
$0 |
Script/shell name |
$1..$9, ${10} |
Positional parameters |
$# |
Number of positional parameters |
$* |
All positional params as single word (with IFS) |
$@ |
All positional params as separate words |
"$*" |
"$1c$2c..." where c = first char of IFS |
"$@" |
"$1" "$2" ... (preserves word boundaries) |
$? |
Exit status of last command |
$$ |
PID of the shell |
$! |
PID of last background command |
$- |
Current option flags |
$_ |
Last argument of previous command |
Compound Commands
Full details: shell-syntax-and-commands.md (section 3.2.5, Compound Commands)
# If
if cmd; then ...; elif cmd; then ...; else ...; fi
# For
for var in words; do ...; done
for (( init; test; step )); do ...; done
# While / Until
while cmd; do ...; done
until cmd; do ...; done
# Case
case word in
pattern1|pattern2) commands ;; # break
pattern3) commands ;& # fall-through
pattern4) commands ;;& # test next
esac
# Select (menu)
select var in words; do ...; done
# Test
[[ expression ]] # Preferred (no word splitting/globbing)
(( expression )) # Arithmetic evaluation
# Grouping
{ commands; } # Current shell (note: space after {, ; before })
( commands ) # Subshell
Test Operators ([[ ]] and test/[ ])
Full details: bash-features.md (section 6.4, Bash Conditional Expressions)
| Operator |
Test |
-e file |
Exists |
-f file |
Regular file |
-d file |
Directory |
-L file / -h file |
Symlink |
-s file |
Non-zero size |
-r file |
Readable |
-w file |
Writable |
-x file |
Executable |
-p file |
Named pipe |
-S file |
Socket |
-b file |
Block device |
-c file |
Character device |
-t fd |
FD is terminal |
-O file |
Owned by effective UID |
-G file |
Owned by effective GID |
-N file |
Modified since last read |
f1 -nt f2 |
f1 newer than f2 |
f1 -ot f2 |
f1 older than f2 |
f1 -ef f2 |
Same inode |
-v var |
Variable is set |
-R var |
Variable is nameref |
-z string |
Zero length |
-n string |
Non-zero length |
s1 == s2 |
Equal (pattern match in [[ ]]) |
s1 != s2 |
Not equal |
s1 < s2 |
Less than (lexicographic) |
s1 > s2 |
Greater than (lexicographic) |
s1 =~ regex |
Regex match ([[ ]] only) |
n1 -eq n2 |
Numeric equal |
n1 -ne n2 |
Numeric not equal |
n1 -lt n2 |
Numeric less than |
n1 -le n2 |
Numeric less/equal |
n1 -gt n2 |
Numeric greater than |
n1 -ge n2 |
Numeric greater/equal |
Redirections
Full details: redirections-and-execution.md (section 3.6, Redirections)
| Syntax |
Operation |
cmd < file |
Stdin from file |
cmd > file |
Stdout to file (truncate) |
cmd >> file |
Stdout to file (append) |
cmd 2> file |
Stderr to file |
cmd &> file or cmd > file 2>&1 |
Stdout+stderr to file |
cmd &>> file or cmd >> file 2>&1 |
Stdout+stderr append |
cmd >| file |
Force overwrite (noclobber) |
cmd <<EOF |
Here document |
cmd <<-EOF |
Here document (strip leading tabs) |
cmd <<< "string" |
Here string |
cmd <&fd |
Duplicate input FD |
cmd >&fd |
Duplicate output FD |
cmd fd<&- |
Close input FD |
cmd fd>&- |
Close output FD |
cmd n<>file |
Open for read+write on FD n |
cmd {var}> file |
Auto-assign FD to var |
Special filenames in redirections: /dev/fd/N, /dev/stdin, /dev/stdout, /dev/stderr, /dev/tcp/host/port, /dev/udp/host/port
Arrays
Full details: bash-features.md (section 6.7, Arrays)
# Indexed arrays
declare -a arr=(one two three)
arr[0]="value"
arr+=(more items)
# Associative arrays (Bash 4.0+)
declare -A map=([key1]=val1 [key2]=val2)
map[key]="value"
# Access
${arr[0]} # Single element
${arr[@]} # All elements (separate words)
${arr[*]} # All elements (single word with IFS)
${#arr[@]} # Number of elements
${!arr[@]} # All indices/keys
${arr[@]:off:len} # Slice
# Unset
unset 'arr[2]' # Remove element (quote to prevent glob)
unset arr # Remove entire array
Expansion Order
- Brace expansion
- Tilde expansion
- Parameter and variable expansion
- Arithmetic expansion
- Command substitution (left-to-right)
- Process substitution
- Word splitting
- Filename expansion (globbing)
- Quote removal
Steps 2-6 happen left-to-right simultaneously. Full details with word-count impacts: functions-parameters-expansions.md (section 3.5).
Common set Options
Full details: shell-builtins.md (section 4.3.1, the set builtin)
| Option |
Effect |
set -e (errexit) |
Exit on error (with exceptions) |
set -u (nounset) |
Error on unset variables |
set -o pipefail |
Pipeline fails if any command fails |
set -x (xtrace) |
Print commands before execution |
set -f (noglob) |
Disable filename expansion |
set -n (noexec) |
Read commands without executing (syntax check) |
set -o posix |
POSIX compliance mode |
set -E (errtrace) |
ERR trap inherited by functions |
set -T (functrace) |
DEBUG/RETURN traps inherited by functions |
Essential shopt Options
Full details: shell-builtins.md (section 4.3.2, the shopt builtin)
| Option |
Effect |
extglob |
Extended patterns: ?(pat) *(pat) +(pat) @(pat) !(pat) |
globstar |
** matches directories recursively |
nullglob |
Unmatched globs expand to nothing |
failglob |
Unmatched globs cause error |
nocaseglob |
Case-insensitive globbing |
nocasematch |
Case-insensitive case and [[ == ]] |
dotglob |
Globs match dotfiles |
lastpipe |
Last pipeline command runs in current shell |
inherit_errexit |
Command substitutions inherit errexit |
assoc_expand_once |
Expand associative array subscripts once |
Trap Signals
Full details: shell-builtins.md (section 4.1, the trap builtin) and redirections-and-execution.md (section 3.7.6, Signals)
trap 'cleanup' EXIT # On shell exit
trap 'handle_err' ERR # On command error (with set -e)
trap 'on_debug' DEBUG # Before every command
trap 'on_return' RETURN # After function/sourced script returns
trap 'handle_int' INT # Ctrl-C
trap 'handle_term' TERM # kill signal
trap '' SIGNAL # Ignore signal
trap - SIGNAL # Reset to default
Arithmetic Operators (inside (( )) and $(( )))
Full details: bash-features.md (section 6.5, Shell Arithmetic)
All C-style operators: +, -, *, /, %, ** (exponent), <<, >>, &, |, ^, ~, !, &&, ||, <, >, <=, >=, ==, !=, =, +=, -=, *=, /=, %=, <<=, >>=, &=, |=, ^=, ++, --, expr?expr:expr (ternary), expr,expr (comma)
Bases: 0x (hex), 0 (octal), base#number (arbitrary base 2-64, e.g. 2#101 for binary). Bash has no 0b binary prefix.
Prompt Escape Sequences
Full details: bash-features.md (section 6.9, Controlling the Prompt)
| Escape |
Meaning |
\u |
Username |
\h |
Hostname (short) |
\H |
Hostname (full) |
\w |
Working directory |
\W |
Basename of working directory |
\d |
Date (Day Mon Date) |
\t |
Time (HH:MM:SS 24hr) |
\T |
Time (HH:MM:SS 12hr) |
\@ |
Time (AM/PM) |
\A |
Time (HH:MM 24hr) |
\D{fmt} |
strftime format |
\j |
Number of jobs |
\! |
History number |
\# |
Command number |
\$ |
# if root, $ otherwise |
\[ |
Begin non-printing chars |
\] |
End non-printing chars |
Definitions
| Term |
Definition |
| blank |
Space or tab |
| word |
Sequence of characters treated as a unit (no unquoted metacharacters) |
| token |
A word or an operator |
| metacharacter |
Unquoted: space, tab, newline, |, &, ;, (, ), <, > |
| control operator |
||, &&, &, ;, ;;, ;&, ;;&, |, |&, (, ), newline |
| name/identifier |
Letters, numbers, underscores; starts with letter or underscore |
| exit status |
0-255; 0 = success, 1 = general error, 2 = usage error, 126 = not executable, 127 = not found, 128+N = killed by signal N |
| special builtin |
POSIX-designated builtins that have special properties (break, :, ., continue, eval, exec, exit, export, readonly, return, set, shift, trap, unset) |
Common Patterns
Safe Script Header
#!/usr/bin/env bash
set -euo pipefail
Temporary Files
tmpfile=$(mktemp) || exit 1
trap 'rm -f "$tmpfile"' EXIT
Read File Line by Line
while IFS= read -r line; do
printf '%s\n' "$line"
done < "$file"
Default Values
name="${1:-default}" # Use default if $1 unset/empty
name="${1:?'missing arg'}" # Exit with error if $1 unset/empty
String Operations
# Lowercase / Uppercase
lower="${str,,}"
upper="${str^^}"
first_cap="${str^}"
# Trim prefix/suffix
filename="${path##*/}" # basename
dir="${path%/*}" # dirname
ext="${file##*.}" # extension
noext="${file%.*}" # remove extension
Array Iteration
for item in "${arr[@]}"; do echo "$item"; done # values
for i in "${!arr[@]}"; do echo "$i: ${arr[$i]}"; done # index: value
Process Substitution
diff <(sort file1) <(sort file2)
while IFS= read -r line; do ...; done < <(cmd) # avoid subshell
Associative Array Check
declare -A map
if [[ -v map["key"] ]]; then echo "exists"; fi
Common Mistakes
Unquoted variables (word splitting + globbing)
# BAD: word splits and globs if file contains spaces or wildcards
for f in $files; do rm $f; done
# GOOD: always quote variable expansions
for f in "${files[@]}"; do rm "$f"; done
[ ] vs [[ ]]
# BAD: word splitting inside [ ] can break with spaces in $var
[ $var == "hello" ] # also: == is not POSIX in [ ]
# GOOD: [[ ]] prevents word splitting and supports == and =~
[[ $var == "hello" ]]
$@ vs $* quoting
# BAD: loses word boundaries
for arg in $@; do echo "$arg"; done
# GOOD: preserves each argument as a separate word
for arg in "$@"; do echo "$arg"; done
# "$*" joins all args into ONE word (separated by first char of IFS)
set -e doesn't trigger everywhere
set -e
# These do NOT cause exit on failure:
if false; then :; fi # test in 'if'
false || true # LHS of ||
false && true # LHS of &&
false | true # pipeline (without pipefail)
! false # negated command
Missing ; before } in brace groups
# BAD: syntax error
{ echo "hello" }
# GOOD: semicolon (or newline) required before }
{ echo "hello"; }
Array access without braces
arr=(one two three)
# BAD: expands $arr (element 0) then appends literal [1]
echo $arr[1] # prints: one[1]
# GOOD: braces required for array subscript
echo "${arr[1]}" # prints: two
Forgetting declare -A for associative arrays
# BAD: creates an indexed array, keys treated as arithmetic (0)
map=([foo]=1 [bar]=2)
echo "${map[foo]}" # prints: 2 (both keys evaluated to index 0)
# GOOD: must declare associative arrays explicitly
declare -A map=([foo]=1 [bar]=2)
echo "${map[foo]}" # prints: 1
Using = vs == in the wrong context
# In [ ] / test: use = (POSIX). == works in Bash but is not portable.
[ "$a" = "$b" ]
# In [[ ]]: both = and == work; RHS is a pattern (quote for literal match)
[[ "$a" == "$b" ]] # literal match (RHS quoted)
[[ "$a" == "$b"* ]] # glob pattern (unquoted * appended)
[[ "$a" == $b ]] # if $b contains *, it's a pattern (RHS unquoted)
Subshell variable loss in pipes
# BAD: read runs in subshell, $var is lost after pipeline
echo "hello" | read var
echo "$var" # empty
# GOOD: use process substitution or lastpipe
read var < <(echo "hello")
echo "$var" # hello
# OR: enable lastpipe (non-interactive, no job control)
shopt -s lastpipe
echo "hello" | read var
local variables use dynamic scoping
inner() { echo "$x"; }
outer() { local x=42; inner; }
outer # prints: 42 (inner sees outer's local!)
# This is dynamic scoping, not lexical. Any function called
# from a scope with a local variable sees that variable.
Here-strings (<<<) add a trailing newline to the stream
cat <<< "hello" | od -An -tx1 # 68 65 6c 6c 6f 0a <- <<< appended a newline
wc -c <<< "hello" # 6 bytes, not 5
# read strips the delimiter, so $var does NOT keep that newline:
read -r var <<< "hello"
printf '%s' "$var" | od -An -tx1 # 68 65 6c 6c 6f (no trailing newline)
# For exact bytes with no newline, feed read from printf:
read -r var < <(printf '%s' "hello")
declare -i silently evaluates strings as arithmetic
declare -i num
num="1+1"
echo "$num" # prints: 2 (string was evaluated!)
# WARNING: with untrusted input this is a code injection vector:
# declare -i x; x="a]$(cmd)" would execute cmd
For handling untrusted input at a script/CLI boundary in general (validate at the edge, never eval it,
pass argv not a shell string, escape per sink), see bitranox:coding-input-sanitization.
trap EXIT is reset in subshells
trap 'echo cleanup' EXIT
(echo "subshell") # EXIT trap does NOT fire here
# Subshells inherit the parent's traps but reset EXIT/ERR/DEBUG/RETURN.
# If you need cleanup in a subshell, set a new trap inside it.
1---2name: coding-bash-reference3description: Use when writing, reviewing, or debugging Bash scripts, when needing exact syntax for shell constructs, parameter expansions, redirections, builtins, test expressions, arrays, or any Bash 5.3 feature. Use when unsure about quoting rules, expansion order, conditional operators, trap behavior, shopt options, or specific builtin options and arguments.4---56# Bash 5.3 Reference78## Overview910Complete reference for GNU Bash 5.3 (May 2025). Covers all shell syntax, builtins, variables, expansions, redirections, and features. Use this skill whenever writing or reviewing bash scripts to ensure correctness.1112**This file is a scannable hub.** Each section below summarizes key constructs with compact tables. Use the Read tool to load referenced files identified as relevant for full syntax, edge cases, and examples:1314- **Syntax & commands** (quoting, compound commands, pipelines): `shell-syntax-and-commands.md`15- **Functions, parameters & expansions** (all expansion types, pattern matching): `functions-parameters-expansions.md`16- **Redirections & execution** (I/O, here docs, FDs, command search, signals): `redirections-and-execution.md`17- **Builtins** (`set`, `shopt`, `declare`, `read`, `printf`, `trap`, etc.): `shell-builtins.md`18- **Variables** (`BASH_REMATCH`, `PIPESTATUS`, `EPOCHSECONDS`, etc.): `shell-variables.md`19- **Bash features** (startup files, arrays, arithmetic, POSIX mode, conditionals): `bash-features.md`20- **Job control, readline & history** (bg/fg, completion, history expansion): `job-control-readline-history.md`2122## When to Use2324- Need exact syntax for any Bash construct (loops, conditionals, expansions, redirections)25- Writing, reviewing, or debugging Bash scripts26- Unsure about quoting rules, expansion order, or operator behavior27- Need to look up a specific builtin, variable, shopt option, or test operator28- Verifying Bash 5.3-specific features (`${ command; }`, `GLOBSORT`, `BASH_MONOSECONDS`)2930## When NOT to Use3132- Writing POSIX-portable `sh` scripts (this covers Bash-specific features beyond POSIX)33- Zsh, Fish, or other shell syntax34- Structuring multi-file Bash projects (use `bitranox:coding-bash-clean-architecture` instead)3536## Before you reach for Bash (and before you ship)3738- **Prefer a Python script over shell for any real logic** (global working rule). Shell has sharp edges39 that bite repeatedly - a leading-dash path makes `dirname`/`grep` treat it as an option, `sed -i`40 can double-apply, and `cmd | head` reports `head`'s exit status not `cmd`'s. For path handling, text41 transforms, or multi-step automation, write a Python (stdlib) script. Reserve Bash for a simple42 one-shot command invocation (including launching a Python script).43- **Gate every Bash script you DO ship with `shellcheck` and `bash -n` before committing** - required44 checks, not optional. `shellcheck -x script.sh` (follows `source`d files) catches quoting,45 word-splitting, and unset-variable bugs; `bash -n script.sh` catches syntax errors without executing46 it. Add `shfmt -i 4 -d script.sh` where the project formats shell.4748## Reference Files4950| File | Contents |51|--------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|52| `shell-syntax-and-commands.md` | Quoting, comments, reserved words, pipelines, lists, compound commands (if/for/while/case/select/[[/(( ), grouping, coprocesses |53| `functions-parameters-expansions.md` | Shell functions, positional/special parameters, ALL expansion types (brace, tilde, parameter, command substitution, arithmetic, process substitution, word splitting, globbing, pattern matching) |54| `redirections-and-execution.md` | All redirection types, here docs/strings, file descriptors, command search/execution, execution environment, exit status, signals, shell scripts |55| `shell-builtins.md` | All Bourne shell builtins, all Bash builtins, `set` options, `shopt` options, special builtins |56| `shell-variables.md` | All Bourne shell variables, all Bash variables (BASH_*, COMP_*, HIST*, READLINE_*, etc.) |57| `bash-features.md` | Invocation options, startup files, interactive shell behavior, conditional expressions, arithmetic, aliases, arrays, directory stack, prompt control, restricted shell, POSIX mode, compatibility mode |58| `job-control-readline-history.md` | Job control (bg/fg/jobs/disown), readline configuration, all bindable commands, vi mode, programmable completion (complete/compgen/compopt), history expansion |5960### Which File Do I Need?6162| I need to... | Read |63|--------------------------------------------------------------------------------------|--------------------------------------|64| Write a function, use parameters/expansions, do string manipulation | `functions-parameters-expansions.md` |65| Use `if`/`for`/`while`/`case`/`select`/`[[ ]]`/`(( ))`, or understand quoting | `shell-syntax-and-commands.md` |66| Redirect I/O, use here docs/strings, understand fd management | `redirections-and-execution.md` |67| Look up a builtin (`set`, `shopt`, `declare`, `read`, `printf`, `trap`, etc.) | `shell-builtins.md` |68| Check a shell variable (`BASH_REMATCH`, `PIPESTATUS`, `EPOCHSECONDS`, etc.) | `shell-variables.md` |69| Understand startup files, arrays, arithmetic, POSIX mode, or conditional expressions | `bash-features.md` |70| Work with job control, readline, completion, or history expansion | `job-control-readline-history.md` |717273## Quick Reference: Most-Used Constructs7475### Quoting7677> Full details: `shell-syntax-and-commands.md` (section 3.1.2, Quoting)7879| Syntax | Behavior |80|-----------|------------------------------------------------------------------|81| `\x` | Escape single character |82| `'text'` | Literal string, no expansion |83| `"text"` | Allows `$`, `` ` ``, `\`, `!` expansion |84| `$'text'` | ANSI-C escapes: `\n`, `\t`, `\e`, `\xHH`, `\uHHHH`, `\UHHHHHHHH` |85| `$"text"` | Locale-specific translation |8687### Parameter Expansion8889> Full details: `functions-parameters-expansions.md` (section 3.5.3)9091| Syntax | Result |92|------------------------|----------------------------------|93| `${var:-default}` | Use default if var unset/null |94| `${var:=default}` | Assign default if var unset/null |95| `${var:+alternate}` | Use alternate if var IS set |96| `${var:?error}` | Error if var unset/null |97| `${#var}` | String length |98| `${var:offset:length}` | Substring |99| `${var#pattern}` | Remove shortest prefix match |100| `${var##pattern}` | Remove longest prefix match |101| `${var%pattern}` | Remove shortest suffix match |102| `${var%%pattern}` | Remove longest suffix match |103| `${var/pat/str}` | Replace first match |104| `${var//pat/str}` | Replace all matches |105| `${var/#pat/str}` | Replace if matches beginning |106| `${var/%pat/str}` | Replace if matches end |107| `${var^pattern}` | Uppercase first char |108| `${var^^pattern}` | Uppercase all chars |109| `${var,pattern}` | Lowercase first char |110| `${var,,pattern}` | Lowercase all chars |111| `${!prefix*}` | Names matching prefix |112| `${!name[@]}` | Array indices/keys |113| `${!var}` | Indirect expansion |114| `${var@Q}` | Quote for reuse |115| `${var@E}` | Expand escape sequences |116| `${var@P}` | Expand as prompt string |117| `${var@A}` | Assignment statement form |118| `${var@a}` | Attribute flags |119| `${var@U}` | Uppercase all |120| `${var@u}` | Uppercase first |121| `${var@L}` | Lowercase all |122| `${var@K}` | Key-value pairs (assoc arrays) |123124### Special Parameters125126> Full details: `functions-parameters-expansions.md` (section 3.4.2, Special Parameters)127128| Param | Meaning |129|---------------------|-------------------------------------------------|130| `$0` | Script/shell name |131| `$1`..`$9`, `${10}` | Positional parameters |132| `$#` | Number of positional parameters |133| `$*` | All positional params as single word (with IFS) |134| `$@` | All positional params as separate words |135| `"$*"` | `"$1c$2c..."` where c = first char of IFS |136| `"$@"` | `"$1" "$2" ...` (preserves word boundaries) |137| `$?` | Exit status of last command |138| `$$` | PID of the shell |139| `$!` | PID of last background command |140| `$-` | Current option flags |141| `$_` | Last argument of previous command |142143### Compound Commands144145> Full details: `shell-syntax-and-commands.md` (section 3.2.5, Compound Commands)146147```bash148# If149if cmd; then ...; elif cmd; then ...; else ...; fi150151# For152for var in words; do ...; done153for (( init; test; step )); do ...; done154155# While / Until156while cmd; do ...; done157until cmd; do ...; done158159# Case160case word in161 pattern1|pattern2) commands ;; # break162 pattern3) commands ;& # fall-through163 pattern4) commands ;;& # test next164esac165166# Select (menu)167select var in words; do ...; done168169# Test170[[ expression ]] # Preferred (no word splitting/globbing)171(( expression )) # Arithmetic evaluation172173# Grouping174{ commands; } # Current shell (note: space after {, ; before })175( commands ) # Subshell176```177178### Test Operators (`[[ ]]` and `test`/`[ ]`)179180> Full details: `bash-features.md` (section 6.4, Bash Conditional Expressions)181182| Operator | Test |183|-----------------------|----------------------------------|184| `-e file` | Exists |185| `-f file` | Regular file |186| `-d file` | Directory |187| `-L file` / `-h file` | Symlink |188| `-s file` | Non-zero size |189| `-r file` | Readable |190| `-w file` | Writable |191| `-x file` | Executable |192| `-p file` | Named pipe |193| `-S file` | Socket |194| `-b file` | Block device |195| `-c file` | Character device |196| `-t fd` | FD is terminal |197| `-O file` | Owned by effective UID |198| `-G file` | Owned by effective GID |199| `-N file` | Modified since last read |200| `f1 -nt f2` | f1 newer than f2 |201| `f1 -ot f2` | f1 older than f2 |202| `f1 -ef f2` | Same inode |203| `-v var` | Variable is set |204| `-R var` | Variable is nameref |205| `-z string` | Zero length |206| `-n string` | Non-zero length |207| `s1 == s2` | Equal (pattern match in `[[ ]]`) |208| `s1 != s2` | Not equal |209| `s1 < s2` | Less than (lexicographic) |210| `s1 > s2` | Greater than (lexicographic) |211| `s1 =~ regex` | Regex match (`[[ ]]` only) |212| `n1 -eq n2` | Numeric equal |213| `n1 -ne n2` | Numeric not equal |214| `n1 -lt n2` | Numeric less than |215| `n1 -le n2` | Numeric less/equal |216| `n1 -gt n2` | Numeric greater than |217| `n1 -ge n2` | Numeric greater/equal |218219### Redirections220221> Full details: `redirections-and-execution.md` (section 3.6, Redirections)222223| Syntax | Operation |224|--------------------------------------|------------------------------------|225| `cmd < file` | Stdin from file |226| `cmd > file` | Stdout to file (truncate) |227| `cmd >> file` | Stdout to file (append) |228| `cmd 2> file` | Stderr to file |229| `cmd &> file` or `cmd > file 2>&1` | Stdout+stderr to file |230| `cmd &>> file` or `cmd >> file 2>&1` | Stdout+stderr append |231| `cmd >| file` | Force overwrite (noclobber) |232| `cmd <<EOF` | Here document |233| `cmd <<-EOF` | Here document (strip leading tabs) |234| `cmd <<< "string"` | Here string |235| `cmd <&fd` | Duplicate input FD |236| `cmd >&fd` | Duplicate output FD |237| `cmd fd<&-` | Close input FD |238| `cmd fd>&-` | Close output FD |239| `cmd n<>file` | Open for read+write on FD n |240| `cmd {var}> file` | Auto-assign FD to var |241242Special filenames in redirections: `/dev/fd/N`, `/dev/stdin`, `/dev/stdout`, `/dev/stderr`, `/dev/tcp/host/port`, `/dev/udp/host/port`243244### Arrays245246> Full details: `bash-features.md` (section 6.7, Arrays)247248```bash249# Indexed arrays250declare -a arr=(one two three)251arr[0]="value"252arr+=(more items)253254# Associative arrays (Bash 4.0+)255declare -A map=([key1]=val1 [key2]=val2)256map[key]="value"257258# Access259${arr[0]} # Single element260${arr[@]} # All elements (separate words)261${arr[*]} # All elements (single word with IFS)262${#arr[@]} # Number of elements263${!arr[@]} # All indices/keys264${arr[@]:off:len} # Slice265266# Unset267unset 'arr[2]' # Remove element (quote to prevent glob)268unset arr # Remove entire array269```270271### Expansion Order2722731. Brace expansion2742. Tilde expansion2753. Parameter and variable expansion2764. Arithmetic expansion2775. Command substitution (left-to-right)2786. Process substitution2797. Word splitting2808. Filename expansion (globbing)2819. Quote removal282283Steps 2-6 happen left-to-right simultaneously. Full details with word-count impacts: `functions-parameters-expansions.md` (section 3.5).284285### Common `set` Options286287> Full details: `shell-builtins.md` (section 4.3.1, the `set` builtin)288289| Option | Effect |290|------------------------|------------------------------------------------|291| `set -e` (`errexit`) | Exit on error (with exceptions) |292| `set -u` (`nounset`) | Error on unset variables |293| `set -o pipefail` | Pipeline fails if any command fails |294| `set -x` (`xtrace`) | Print commands before execution |295| `set -f` (`noglob`) | Disable filename expansion |296| `set -n` (`noexec`) | Read commands without executing (syntax check) |297| `set -o posix` | POSIX compliance mode |298| `set -E` (`errtrace`) | ERR trap inherited by functions |299| `set -T` (`functrace`) | DEBUG/RETURN traps inherited by functions |300301### Essential `shopt` Options302303> Full details: `shell-builtins.md` (section 4.3.2, the `shopt` builtin)304305| Option | Effect |306|---------------------|-----------------------------------------------------------------|307| `extglob` | Extended patterns: `?(pat)` `*(pat)` `+(pat)` `@(pat)` `!(pat)` |308| `globstar` | `**` matches directories recursively |309| `nullglob` | Unmatched globs expand to nothing |310| `failglob` | Unmatched globs cause error |311| `nocaseglob` | Case-insensitive globbing |312| `nocasematch` | Case-insensitive `case` and `[[ == ]]` |313| `dotglob` | Globs match dotfiles |314| `lastpipe` | Last pipeline command runs in current shell |315| `inherit_errexit` | Command substitutions inherit `errexit` |316| `assoc_expand_once` | Expand associative array subscripts once |317318### Trap Signals319320> Full details: `shell-builtins.md` (section 4.1, the `trap` builtin) and `redirections-and-execution.md` (section 3.7.6, Signals)321322```bash323trap 'cleanup' EXIT # On shell exit324trap 'handle_err' ERR # On command error (with set -e)325trap 'on_debug' DEBUG # Before every command326trap 'on_return' RETURN # After function/sourced script returns327trap 'handle_int' INT # Ctrl-C328trap 'handle_term' TERM # kill signal329trap '' SIGNAL # Ignore signal330trap - SIGNAL # Reset to default331```332333### Arithmetic Operators (inside `(( ))` and `$(( ))`)334335> Full details: `bash-features.md` (section 6.5, Shell Arithmetic)336337All C-style operators: `+`, `-`, `*`, `/`, `%`, `**` (exponent), `<<`, `>>`, `&`, `|`, `^`, `~`, `!`, `&&`, `||`, `<`, `>`, `<=`, `>=`, `==`, `!=`, `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `<<=`, `>>=`, `&=`, `|=`, `^=`, `++`, `--`, `expr?expr:expr` (ternary), `expr,expr` (comma)338339Bases: `0x` (hex), `0` (octal), `base#number` (arbitrary base 2-64, e.g. `2#101` for binary). Bash has no `0b` binary prefix.340341### Prompt Escape Sequences342343> Full details: `bash-features.md` (section 6.9, Controlling the Prompt)344345| Escape | Meaning |346|-----------|-------------------------------|347| `\u` | Username |348| `\h` | Hostname (short) |349| `\H` | Hostname (full) |350| `\w` | Working directory |351| `\W` | Basename of working directory |352| `\d` | Date (Day Mon Date) |353| `\t` | Time (HH:MM:SS 24hr) |354| `\T` | Time (HH:MM:SS 12hr) |355| `\@` | Time (AM/PM) |356| `\A` | Time (HH:MM 24hr) |357| `\D{fmt}` | strftime format |358| `\j` | Number of jobs |359| `\!` | History number |360| `\#` | Command number |361| `\$` | `#` if root, `$` otherwise |362| `\[` | Begin non-printing chars |363| `\]` | End non-printing chars |364365## Definitions366367| Term | Definition |368|----------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|369| **blank** | Space or tab |370| **word** | Sequence of characters treated as a unit (no unquoted metacharacters) |371| **token** | A word or an operator |372| **metacharacter** | Unquoted: space, tab, newline, `\|`, `&`, `;`, `(`, `)`, `<`, `>` |373| **control operator** | `\|\|`, `&&`, `&`, `;`, `;;`, `;&`, `;;&`, `\|`, `\|&`, `(`, `)`, newline |374| **name/identifier** | Letters, numbers, underscores; starts with letter or underscore |375| **exit status** | 0-255; 0 = success, 1 = general error, 2 = usage error, 126 = not executable, 127 = not found, 128+N = killed by signal N |376| **special builtin** | POSIX-designated builtins that have special properties (break, :, ., continue, eval, exec, exit, export, readonly, return, set, shift, trap, unset) |377378## Common Patterns379380### Safe Script Header381```bash382#!/usr/bin/env bash383set -euo pipefail384```385386### Temporary Files387```bash388tmpfile=$(mktemp) || exit 1389trap 'rm -f "$tmpfile"' EXIT390```391392### Read File Line by Line393```bash394while IFS= read -r line; do395 printf '%s\n' "$line"396done < "$file"397```398399### Default Values400```bash401name="${1:-default}" # Use default if $1 unset/empty402name="${1:?'missing arg'}" # Exit with error if $1 unset/empty403```404405### String Operations406```bash407# Lowercase / Uppercase408lower="${str,,}"409upper="${str^^}"410first_cap="${str^}"411412# Trim prefix/suffix413filename="${path##*/}" # basename414dir="${path%/*}" # dirname415ext="${file##*.}" # extension416noext="${file%.*}" # remove extension417```418419### Array Iteration420```bash421for item in "${arr[@]}"; do echo "$item"; done # values422for i in "${!arr[@]}"; do echo "$i: ${arr[$i]}"; done # index: value423```424425### Process Substitution426```bash427diff <(sort file1) <(sort file2)428while IFS= read -r line; do ...; done < <(cmd) # avoid subshell429```430431### Associative Array Check432```bash433declare -A map434if [[ -v map["key"] ]]; then echo "exists"; fi435```436437## Common Mistakes438439### Unquoted variables (word splitting + globbing)440441```bash442# BAD: word splits and globs if file contains spaces or wildcards443for f in $files; do rm $f; done444445# GOOD: always quote variable expansions446for f in "${files[@]}"; do rm "$f"; done447```448449### `[ ]` vs `[[ ]]`450451```bash452# BAD: word splitting inside [ ] can break with spaces in $var453[ $var == "hello" ] # also: == is not POSIX in [ ]454455# GOOD: [[ ]] prevents word splitting and supports == and =~456[[ $var == "hello" ]]457```458459### `$@` vs `$*` quoting460461```bash462# BAD: loses word boundaries463for arg in $@; do echo "$arg"; done464465# GOOD: preserves each argument as a separate word466for arg in "$@"; do echo "$arg"; done467468# "$*" joins all args into ONE word (separated by first char of IFS)469```470471### `set -e` doesn't trigger everywhere472473```bash474set -e475# These do NOT cause exit on failure:476if false; then :; fi # test in 'if'477false || true # LHS of ||478false && true # LHS of &&479false | true # pipeline (without pipefail)480! false # negated command481```482483### Missing `;` before `}` in brace groups484485```bash486# BAD: syntax error487{ echo "hello" }488489# GOOD: semicolon (or newline) required before }490{ echo "hello"; }491```492493### Array access without braces494495```bash496arr=(one two three)497498# BAD: expands $arr (element 0) then appends literal [1]499echo $arr[1] # prints: one[1]500501# GOOD: braces required for array subscript502echo "${arr[1]}" # prints: two503```504505### Forgetting `declare -A` for associative arrays506507```bash508# BAD: creates an indexed array, keys treated as arithmetic (0)509map=([foo]=1 [bar]=2)510echo "${map[foo]}" # prints: 2 (both keys evaluated to index 0)511512# GOOD: must declare associative arrays explicitly513declare -A map=([foo]=1 [bar]=2)514echo "${map[foo]}" # prints: 1515```516517### Using `=` vs `==` in the wrong context518519```bash520# In [ ] / test: use = (POSIX). == works in Bash but is not portable.521[ "$a" = "$b" ]522523# In [[ ]]: both = and == work; RHS is a pattern (quote for literal match)524[[ "$a" == "$b" ]] # literal match (RHS quoted)525[[ "$a" == "$b"* ]] # glob pattern (unquoted * appended)526[[ "$a" == $b ]] # if $b contains *, it's a pattern (RHS unquoted)527```528529### Subshell variable loss in pipes530531```bash532# BAD: read runs in subshell, $var is lost after pipeline533echo "hello" | read var534echo "$var" # empty535536# GOOD: use process substitution or lastpipe537read var < <(echo "hello")538echo "$var" # hello539540# OR: enable lastpipe (non-interactive, no job control)541shopt -s lastpipe542echo "hello" | read var543```544545### `local` variables use dynamic scoping546547```bash548inner() { echo "$x"; }549outer() { local x=42; inner; }550outer # prints: 42 (inner sees outer's local!)551552# This is dynamic scoping, not lexical. Any function called553# from a scope with a local variable sees that variable.554```555556### Here-strings (`<<<`) add a trailing newline to the stream557558```bash559cat <<< "hello" | od -An -tx1 # 68 65 6c 6c 6f 0a <- <<< appended a newline560wc -c <<< "hello" # 6 bytes, not 5561# read strips the delimiter, so $var does NOT keep that newline:562read -r var <<< "hello"563printf '%s' "$var" | od -An -tx1 # 68 65 6c 6c 6f (no trailing newline)564# For exact bytes with no newline, feed read from printf:565read -r var < <(printf '%s' "hello")566```567568### `declare -i` silently evaluates strings as arithmetic569570```bash571declare -i num572num="1+1"573echo "$num" # prints: 2 (string was evaluated!)574# WARNING: with untrusted input this is a code injection vector:575# declare -i x; x="a]$(cmd)" would execute cmd576```577578For handling untrusted input at a script/CLI boundary in general (validate at the edge, never eval it,579pass argv not a shell string, escape per sink), see `bitranox:coding-input-sanitization`.580581### `trap EXIT` is reset in subshells582583```bash584trap 'echo cleanup' EXIT585(echo "subshell") # EXIT trap does NOT fire here586# Subshells inherit the parent's traps but reset EXIT/ERR/DEBUG/RETURN.587# If you need cleanup in a subshell, set a new trap inside it.588```