Bash Scripting Syntax, Parameter Expansion & Error Traps Reference
Master bash conditionals, loops, string slicing, stream redirection (2>&1), exit traps, and safe shell scripting practices.
Table of Contents
The Unofficial Bash Strict Mode Header
Place these directives at the very top of every production bash script to catch errors immediately.
| Directive | Flag Meaning | Why It Matters |
|---|---|---|
| `set -e` | Exit immediately if any command returns non-zero status | Prevents script from continuing into destructive operations following a failure |
| `set -u` | Treat unset variables as fatal errors | Protects against catastrophic typos like `rm -rf $DIR/` when DIR is unset |
| `set -o pipefail` | Pipeline returns status of last command that errored | Catches errors in pipelines like `failing_cmd | grep pattern` |
| `IFS=$'\n\t'` | Internal Field Separator set to newline and tab | Prevents accidental splitting on spaces inside file path variables |
Parameter Expansion & Default Values
Clean variable manipulation without invoking subshells or external sed/awk processes.
| Syntax Pattern | Operation & Description | Example Result |
|---|---|---|
| `${VAR:-default}` | Use default if VAR is unset or empty | `${PORT:-3000}` resolves to 3000 if PORT is null |
| `${VAR:=default}` | Assign default to VAR if unset or empty | Sets and returns value of default |
| `${VAR:?error_msg}` | Display error message and abort if VAR is unset | `${API_KEY:?"API_KEY is required"}` |
| `${#VAR}` | Return character length of variable string | `"apple"` returns 5 |
| `${VAR##*.}` | Extract file extension (strip everything before last dot) | `"doc.pdf"` returns `"pdf"` |
Stream Redirection & File Descriptors
Controlling standard input (0), standard output (1), and standard error (2).
| Redirection Code | Target Stream Destination | Common Use Case |
|---|---|---|
| `> file.txt` | Redirect stdout to file (overwrites) | Save build log output |
| `>> file.txt` | Append stdout to end of file | Continuous server log appending |
| `2>&1` | Redirect stderr into stdout stream | Send errors together with normal output to pipe |
| `&> /dev/null` | Discard BOTH stdout and stderr completely | Silent background execution |
Frequently Asked Questions
How do I ensure temporary files are deleted when a script exits or crashes?
Use the `trap` command: `cleanup() { rm -rf "$TEMP_DIR"; }; trap cleanup EXIT ERR SIGINT SIGTERM`. This guarantees the cleanup function executes even if the script is interrupted with Ctrl+C.
What is the difference between single brackets [ and double brackets [[ in bash?
Double brackets `[[ ... ]]` is the modern enhanced test command in Bash. It supports regex matching (`=~`), prevents word-splitting on variables without quotes, and supports `&&` / `||` logical operators inside the test block.