Skip to main content
Linux & CLI

Advanced Bash Scripting & Shell

Essential

Bash automation recipes, safety flags (set -euo pipefail), parameter expansion, traps, and subshells.

Instant Copy & SearchProduction Flagged SyntaxCurrent Flag Reference

Advanced Bash Scripting & Shell Interactive Command Directory

Browse, search, and copy battle-tested commands & syntax recipes (16 Total Commands).

16+ Verified Recipes
Script Safety Headerset -euo pipefail
set -euo pipefail IFS=$'\n\t'

Exit immediately on command errors (-e), unset variables (-u), and pipeline failures (-o pipefail).

Parameter Expansion${var##*.} ${var:-default}
FILE_EXT="${FILENAME##*.}" DIR_NAME="${FULL_PATH%/*}" DEFAULT_VAL="${ENV_VAR:-fallback_value}"

Extract file extension, parent directory path, or provide fallback default values without external binaries.

Cleanup Trapstrap '...' EXIT
TMP_DIR=$(mktemp -d) trap 'rm -rf "$TMP_DIR"' EXIT

Guarantee temporary scratch directory is deleted whenever script exits or aborts.

Array Iteration"${arr[@]}"
SERVICES=("nginx" "redis" "postgres") for s in "${SERVICES[@]}"; do systemctl is-active --quiet "$s" || echo "$s is DOWN" done

Loop safely over whitespace-containing array elements with full quotation.

Conditionals[[ -f && -s ]]
if [[ -f "$FILE" && -s "$FILE" ]]; then echo "File exists and is not empty" fi

Use modern [[ ]] syntax for regex and multi-condition comparisons.

Command Substitution$(cmd 2>/dev/null)
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")

Capture stdout of subshell while suppressing stderr messages.

File IterationIFS=, read -r
while IFS= read -r line; do echo "Processing: $line" done < input.txt

Safely iterate over file line-by-line without truncating leading or trailing whitespace, preserving backslash escapes.

Defensive Coding-z, :-, >&2
[[ -z "${MY_VAR:-}" ]] && { echo "Error: MY_VAR is required" >&2; exit 1; }

Validate mandatory environment variables under strict mode without crashing on unbound variable checks.

Control Flowcase, in, esac
case "$ENV" in staging) echo "Deploying staging";; production) echo "Deploying prod";; *) echo "Invalid environment"; exit 1;; esac

Pattern-matching switch statement for multi-environment conditional deployment orchestration.

I/O Redirectionexec, tee, 2>&1
exec 3>&1 4>&2 > >(tee -a script.log) 2>&1

Duplicate file descriptors to log all standard output and standard error simultaneously to terminal and persistent logfile.

Parallel Execution-P, -n, -I
xargs -P 4 -n 1 -I {} bash -c 'echo "Processing {}"' < urls.txt

Run 4 concurrent background worker processes across input lines utilizing multiple CPU cores.

Safe File Handling-print0, -d ''
find . -maxdepth 2 -type f -print0 | while IFS= read -r -d '' file; do echo "Found: $file" done

Traverse directory trees safely using null-byte delimiters immune to filenames containing spaces, newlines, and quotes.

Subshell & Timerstimeout, -sSf
timeout 15s curl -sSf https://api.service.internal/health || echo "Health check timed out"

Execute network health checks bounded by strict wall-clock timeouts preventing hung cron jobs.

Process Substitution<(...)
diff -u <(sort file1.txt) <(sort file2.txt)

Compare outputs of two sub-commands dynamically without creating intermediate disk files.

Path ResolutionBASH_SOURCE, dirname, pwd
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"

Resolve absolute directory path of the executing Bash script regardless of caller working directory.

JSON Parsingpython3 -c
python3 -c "import json, sys; print(json.load(sys.stdin)['status'])" < data.json

Safely extract JSON keys in environments lacking jq using native Python standard library.

Zero Setup100% In-Browser Execution

Companion Developer Tools & Playgrounds

Accelerate command execution and syntax debugging with HelloAIHub suite of interactive tools.

Explore all developer tools

Advanced Bash Scripting & Shell: Command Groups & Quick Index

16 indexed entries across 16 sections
Script Safety Header1 items
Parameter Expansion1 items
Cleanup Traps1 items
Array Iteration1 items
Conditionals1 items
Command Substitution1 items
File Iteration1 items
Defensive Coding1 items
Control Flow1 items
I/O Redirection1 items
Parallel Execution1 items
Safe File Handling1 items
Subshell & Timers1 items
Process Substitution1 items
Path Resolution1 items
JSON Parsing1 items

Highlighted Flags & Syntax Examples in Advanced Bash Scripting & Shell

set -euo pipefail IFS=$'\n\t'

Exit immediately on command errors (-e), unset variables (-u), and pipeline failures (-o pipefail).

Flags: set -euo pipefail
FILE_EXT="${FILENAME##*.}" DIR_NAME="${FULL_PATH%/*}" DEFAULT_VAL="${ENV_VAR:-fallback_value}"

Extract file extension, parent directory path, or provide fallback default values without external binaries.

Flags: ${var##*.} ${var:-default}
TMP_DIR=$(mktemp -d) trap 'rm -rf "$TMP_DIR"' EXIT

Guarantee temporary scratch directory is deleted whenever script exits or aborts.

Flags: trap '...' EXIT
SERVICES=("nginx" "redis" "postgres") for s in "${SERVICES[@]}"; do systemctl is-active --quiet "$s" || echo "$s is DOWN" done

Loop safely over whitespace-containing array elements with full quotation.

Flags: "${arr[@]}"

Frequently Asked Questions

Expert recommendations, common traps, and production best practices for Advanced Bash Scripting & Shell.

Why is 'set -euo pipefail' called the unofficial Bash strict mode?

By default, Bash continues executing even when commands fail, treats undeclared variables as empty strings, and ignores errors on the left side of pipes. 'set -euo pipefail' stops execution on any failure, preventing cascading errors and data loss.

What is the difference between [ ] and [[ ]] in Bash?

[ is a standard POSIX test command. [[ is a Bash keyword that supports pattern matching, regular expression comparisons (=~), and does not require word splitting or filename expansion on variable references.

Why should you always quote variable expansions as "$VAR" in Bash scripts?

Unquoted expansions undergo Word Splitting and Pathname Expansion (globbing). If $VAR contains spaces, tabs, or wildcards like '*', Bash splits the value into multiple distinct positional arguments or expands it into local file paths, resulting in subtle bugs or command injection vulnerabilities.

What is process substitution (<(command)) and how does it differ from a pipe (|)?

Process substitution (<(command)) runs a sub-process and presents its output as a named file descriptor (e.g. /dev/fd/63). Unlike pipes which feed standard input to the next process, process substitution allows commands expecting file path arguments (like 'diff', 'comm', or multiple inputs) to consume dynamic command streams without temp files.

What is the purpose of IFS=$'\n\t' in production shell scripts?

IFS (Internal Field Separator) controls how Bash splits word boundaries. The default IFS is space, tab, and newline. Setting IFS=$'\n\t' removes the space character from field splitting, ensuring that filenames and string variables containing spaces are not accidentally chopped into multiple tokens.

How do traps work in Bash and how can you ensure cleanup code executes on premature exits or crashes?

The 'trap' command registers a callback handler for kernel signals (SIGINT, SIGTERM, SIGHUP) and pseudo-signals like EXIT. Registering 'trap 'rm -rf "$TMP_DIR"' EXIT' guarantees that temporary resources are cleanly unlinked when the script terminates normally or aborts due to 'set -e' errors.

Cross-Hub Skill Acceleration

Combine command lookups with active coding interviews and complete career paths.

Need More Cheat Sheets?

Explore developer cheat sheets and syntax guides on HelloAIHub.

Browse All Cheat Sheets