Use strict mode with a safe IFS

Stop on errors, unset variables and failed pipes. Split words only on newline and tab

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

tool
bash12 commands
tags
bashtroubleshootingci

More bash commands

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

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

  • 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

all 12 bash commands