Overview
This card is the lookup table for Bash syntax you forget: parameter expansion, traps, arithmetic, and tests. File search and text-processing one-liners are in find-grep-awk-sed; strict-mode and quoting rules are in shell. Examples assume Bash 4 or newer.
Parameter expansion
Prefer these over forking sed or basename. Examples use f=path/to/file.tar.gz.
| Expansion | Result |
|---|---|
${f##*/} | file.tar.gz (basename) |
${f%/*} | path/to (dirname) |
${f%.*} / ${f%%.*} | path/to/file.tar / path/to/file |
${f#*.} | tar.gz (after the first dot) |
${f//\//-} | path-to-file.tar.gz |
${f^^} / ${f,,} | Upper / lower case |
${name:-default} | default if unset or empty |
${name:?message} | Exit with message if unset |
${#name} | Length |
Jobs and traps
Clean up with trap ... EXIT so cleanup runs on every exit path.
| One-liner | Effect |
|---|---|
cmd & / jobs / wait [$PID] | Background / list / block until done. |
disown %1 | Remove job 1 from the shell so a hangup does not kill it. |
nohup cmd > out.log 2>&1 & | Detach from the terminal. |
trap 'rm -rf "$TMP"' EXIT | Cleanup on normal and error exit. |
trap 'echo interrupted; exit 130' INT | Handle Ctrl-C. |
TMP=$(mktemp -d) | Safe temporary directory. |
Arithmetic and tests
Bash arithmetic is integer-only; use bc or awk for decimals.
| One-liner | Effect |
|---|---|
(( count++ )) / echo $(( 3 * (4 + 5) )) | Increment / inline arithmetic (27). |
echo "scale=2; 7/3" | bc | Decimal division (2.33). |
[[ -f f ]] / [[ -d d ]] / [[ -z $v ]] | File exists / directory exists / empty or unset. |
[[ $a == "yes" ]] / [[ $s =~ ^[0-9]+$ ]] | String equality / regex match. |
Prefer [[ ... ]] over [ ... ]: no word splitting, and it supports patterns and regex.
Gotchas
Avoid these; each fails silently in a script.
| Gotcha | Fix |
|---|---|
Unquoted $var word-splits and globs. | Write "$var". |
cd "$dir" failing leaves the script running in the wrong directory. | cd "$dir" || exit 1, or set -e. |
| A pipeline’s exit status hides earlier failures. | set -o pipefail. |
for f in *.md yields the literal *.md when nothing matches. | shopt -s nullglob. |
read strips whitespace and eats backslashes. | read -r line. |
| Backticks do not nest cleanly. | Use $(...). |
${f^^}, mapfile, and associative arrays fail on Bash 3.2. | Check bash --version on macOS scripts. |