brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: [[ $s =~ regex ]] fills BASH_REMATCH with the parts that matched

Bash
~/tips/tip-bash-regex-match-bash-rematch

v="sonarr-4.0.10"

Matches a regular expression in bash and gives you the captured parts without sed.

Need one number out of a version string? The usual reflex is grep -o or sed with capture groups. Bash can match a regular expression on its own and hand you the captured pieces in an array.

Inside [[ ]], the =~ operator matches the left side against a POSIX extended regular expression. When it matches, bash puts the whole match in BASH_REMATCH[0] and each group in parentheses in the next index:

v="sonarr-4.0.10"
if [[ $v =~ ^([a-z]+)-([0-9]+)\.([0-9]+) ]]; then
  echo "app:   ${BASH_REMATCH[1]}"   # sonarr
  echo "major: ${BASH_REMATCH[2]}"   # 4
  echo "minor: ${BASH_REMATCH[3]}"   # 0
fi

The return code tells you whether it matched (0), didn’t match (1) or the regex itself is broken (2), so it slots straight into an if. Without ^ and $ the pattern may match any part of the string, which surprises people who expect a full match.

The big caveat is quoting. Anything quoted on the right side is matched as plain text, so [[ $v =~ "^v[0-9]+$" ]] looks for those literal characters and never matches a version. My advice is to put the regex in a variable and use it unquoted:

re='^v([0-9]+)$'
[[ $tag =~ $re ]] && echo "release ${BASH_REMATCH[1]}"

That also saves you from fighting bash over spaces and brackets in the pattern. And the next =~ overwrites BASH_REMATCH, so copy the values into your own variables before you match again. The manual also warns against declaring BASH_REMATCH as a local variable.

Further reading: bash(1) manual page

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link