Regex Bash Condition Matching

Use bash regex conditional matching with BASH_REMATCH to extract capture groups from structured input strings.

BashData Integrity

Code

bashsnippet
19 lines
#!/usr/bin/env bash
set -euo pipefail

parse_version() {
  local str=$1
  if [[ ${str} =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)(-([a-z0-9.]+))?$ ]]; then
    local major=${BASH_REMATCH[1]}
    local minor=${BASH_REMATCH[2]}
    local patch=${BASH_REMATCH[3]}
    local pre=${BASH_REMATCH[5]:-release}
    echo "major=${major} minor=${minor} patch=${patch} pre=${pre}"
  else
    echo "Invalid version: ${str}" >&2
    return 1
  fi
}

parse_version "1.2.3-beta.1"
parse_version "4.5.6"

How it works

The shebang line is backed by set -euo pipefail: first failure stops the run, unset variables are errors, and a pipeline fails if any stage fails.

The work is delegated to parse_version, chained so each stage’s output feeds the next.

A helper function (parse_version) keeps the repeated logic out of the main flow.

The script leans on parameter expansion 10 times, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Which external commands does the script rely on?
`parse_version` must be available on the PATH environment variable; everything else is shell built-in syntax.