Linux & DevOps ReferenceUpdated: 2026-11-06

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.

Bash (Bourne Again SHell) is the default command processor on most Linux distributions and macOS terminals. From CI/CD automation pipelines to local developer environments, understanding defensive scripting practices, parameter expansion, and error traps prevents silent production failures.

The Unofficial Bash Strict Mode Header

Place these directives at the very top of every production bash script to catch errors immediately.

DirectiveFlag MeaningWhy It Matters
`set -e`Exit immediately if any command returns non-zero statusPrevents script from continuing into destructive operations following a failure
`set -u`Treat unset variables as fatal errorsProtects against catastrophic typos like `rm -rf $DIR/` when DIR is unset
`set -o pipefail`Pipeline returns status of last command that erroredCatches errors in pipelines like `failing_cmd | grep pattern`
`IFS=$'\n\t'`Internal Field Separator set to newline and tabPrevents accidental splitting on spaces inside file path variables

Parameter Expansion & Default Values

Clean variable manipulation without invoking subshells or external sed/awk processes.

Syntax PatternOperation & DescriptionExample 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 emptySets 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 CodeTarget Stream DestinationCommon Use Case
`> file.txt`Redirect stdout to file (overwrites)Save build log output
`>> file.txt`Append stdout to end of fileContinuous server log appending
`2>&1`Redirect stderr into stdout streamSend errors together with normal output to pipe
`&> /dev/null`Discard BOTH stdout and stderr completelySilent 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.