Clean up a temp dir with trap

Remove the mktemp dir on exit or signal. Note: quote $tmp so paths with spaces work

tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT INT TERM

tool
bash12 commands
tags
bashsecuritytroubleshooting

More bash commands

  • diff <(kubectl get cm a -o yaml) <(kubectl get cm b -o yaml)

    Process substitution compares two outputs without temp files

  • mapfile -t lines < file.txt; printf '%s\n' "${lines[@]}"

    mapfile -t strips newlines and keeps spaces, unlike word splitting in a for loop

  • f=/var/log/app.log.gz; echo "${f##*/}" "${f%.*}" "${f//log/LOG}"

    Get the basename, strip the extension and replace text without calling sed or basename

  • [[ $s =~ ^([0-9]+)\.([0-9]+) ]] && echo "${BASH_REMATCH[1]}/${BASH_REMATCH[2]}"

    Built-in regex match that extracts groups. Note: do not quote the regex on the right side

  • find . -name '*.log' -print0 | xargs -0 -P"$(nproc)" -n1 gzip

    Run one job per CPU core. NUL separators keep file names with spaces safe

all 12 bash commands