Regex Bash Condition Matching
Use bash regex conditional matching with BASH_REMATCH to extract capture groups from structured input strings.
Code
#!/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
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.