Check if a version string is in valid SemVer format

re_semver=...; perl -wln -e "/$re_semver/ or exit(1)" <<< "$version"

October 4, 2023bashoneliners

Explanation

With Semantic Versioning, a version number looks like 2.1.3, with MAJOR.MINOR.PATCH parts. See details on https://semver.org/.

The one-liner checks whether the version string in $version is in valid SemVer format, exiting with success or failure accordingly.

For this we first need to define the regular expression pattern in re_semver, which is no picnic, thankfully we can copy-paste the latest value from https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string, enclosed within single-quotes:

re_semver='^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$'

With this now we can check some version numbers:

$ perl -wln -e "/$re_semver/ or exit(1)" <<< "1.2.3"
# success

$ perl -wln -e "/$re_semver/ or exit(1)" <<< "v1.2.3"
# fail

$ perl -wln -e "/$re_semver/ or exit(1)" <<< "1.2.3-beta"
# success

$ perl -wln -e "/$re_semver/ or exit(1)" <<< "1.2.x"
# fail

The -wln flags of Perl is a useful idiom for Perl one-liners:

  • -w: prints warnings about dubious constructs
  • -l: automatically chomps input lines, removing trailing spaces
  • -n: wraps the Perl one-liner in a loop for line-by-line processing
  • -e EXPR: is the Perl expression we want to execute for each line in the input

See more details about Perl's flags in man perlrun.

The Perl command we execute here means simply match the input line against $re_semver or else exit with failure. We provide the input line using a here-string with the <<< "..." syntax.

An alternative of this Perl one-liner:

grep -qP "$re_semver" <<< "$version"

The key in this grep is using the P flag to enable the PCRE (Perl) regular expression engine, which is a GNU extension, making it not portable. If you need to use Perl regular expressions, then Perl is most probably installed in the system, so it's better to just use Perl directly and have a portable solution.