Bash Expert
Overview
- •Write safe Bash scripts and one-liners with correct quoting, piping, and error handling.
- •Produce portable code for macOS/Linux; call out GNU vs BSD differences and POSIX-only paths when needed.
- •Debug issues (tracing, ShellCheck) and propose tests/dry-runs before destructive actions.
Quick Start
- •Confirm shell/OS/permissions. Note macOS ships Bash 3.2 (no associative arrays); prefer Bash 4+ when available.
- •Choose shebang:
/usr/bin/env bashfor Bash 4+,/bin/shfor POSIX-only requirements. - •Default safety (non-interactive):
Avoid strict mode when partial failures are expected.code
set -euo pipefail IFS=$'\n\t' shopt -s nullglob
- •Quote everything (
"${var}"), preferprintfoverecho, and avoid word-splitting in loops.
Workflow for Script Requests
- •Clarify goal, inputs, side effects, and scale (file counts, data size).
- •Identify tools (
find,grep,sed,awk,jq,tar,rsync, etc.) and portability constraints. - •Scaffold with logging and cleanup:
code
#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' trap 'cleanup' EXIT cleanup(){ :; } log(){ printf '%s\n' "$*" >&2; } die(){ log "error: $*"; exit 1; } - •Add argument parsing (
getopts), sanity checks, and dry-run mode before mutating data. - •Use safe loops (
while IFS= read -r line; do ...; done < file) and null-delimited traversal (find ... -print0 | while IFS= read -r -d '' path; do ...; done). - •Validate (
bash -n,shellcheck -x), run with representative inputs, then present final command plus usage notes/rollback guidance.
One-Liners & Pipelines
- •Keep pipelines fail-fast with
set -o pipefailorbash -o pipefail -c 'cmd'. - •Prefer process substitution over temp files when possible:
diff <(cmd1) <(cmd2). - •Use
xargs -0 -rwithfind -print0; avoidfor f in $(...). - •Set
LC_ALL=Cfor deterministic greps/sorts; specify PATH explicitly for cron/CI runs.
Portability & Performance
- •Bash-only features: arrays,
[[ ]], brace expansion,**globstar. Offer POSIX alternatives when/bin/shis requested. - •BSD vs GNU flags:
sed -Evs-r,datevsgdate,statvsgstat; note fallbacks for macOS. - •Prefer built-ins where possible; for large data sets, use
awk/perlinstead of large Bash loops.
Debugging & Validation
- •Trace with
set -x(orbash -x script.sh); usePS4='+ ${BASH_SOURCE}:${LINENO}: 'for context. - •
shellcheck script.shfor linting; address quoting and word-splitting warnings first. - •Log intermediates with
printf '%s\n' "msg: $var"; disable tracing after debug. - •Provide dry-run flags and confirmation prompts before destructive actions.
References
See references/bash_patterns.md for ready-to-use snippets: script skeletons, getopts template, safe find/xargs, mktemp + traps, heredocs, array handling, and bats test scaffolding. Load it only when deeper examples are needed.