Capture regex groups with BASH_REMATCH

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

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

tool
bash12 commands
tags
bashdebug

More bash commands

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

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

  • curl -s "$url" | jq .data; echo "${PIPESTATUS[@]}"

    Show the exit code of every command in a pipe. $? only gives the last one

  • while getopts "n:v" o; do case $o in n) ns=$OPTARG;; v) verbose=1;; esac; done

    POSIX option parsing: -n takes a value, -v is a simple switch

  • timeout -k 5s 30s ./long_task.sh || echo "timed out: $?"

    Sends SIGTERM after 30s, then SIGKILL 5s later. Exit code 124 means the command timed out

  • exec 3>>audit.log; echo "$(date -Is) start" >&3; exec 3>&-

    Open fd 3 to a file, write to it separately from stdout, then close it

all 12 bash commands