Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate that a version number is valid using a regexp in bash?

Tags:

regex

bash

I am trying to validate that the version number is matching a version pattern but it seems that the check fails for some weird reason.

#!/bin/bash
VERSION="1.2.3"
if [[ $VERSION =~ ^(\d+\.)?(\d+\.)?(\*|\d+)$ ]]; then
 echo "INFO:<-->Version $VERSION"
else
 echo "ERROR:<->Unable to validate package version: '$VERSION'"
 exit 1
fi
like image 489
sorin Avatar asked Mar 09 '16 14:03

sorin


People also ask

How do you check if a string matches a regex in Bash?

You can use the test construct, [[ ]] , along with the regular expression match operator, =~ , to check if a string matches a regex pattern (documentation). where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.

Can you use regex in Bash?

Regex is a very powerful tool that is available at our disposal & the best thing about using regex is that they can be used in almost every computer language. So if you are Bash Scripting or creating a Python program, we can use regex or we can also write a single line search query.

What =~ in Bash?

A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.

How do I determine Bash script version?

To find my bash version, run any one of the following command: Get the version of bash I am running, type: echo "${BASH_VERSION}" Check my bash version on Linux by running: bash --version. To display bash shell version press Ctrl + x Ctrl + v.


1 Answers

You should use [0-9] or [[:digit:]] in Bash instead of \d (as Bash does not support this shorthand character class), and I suggest shortening the pattern with the help of a limiting quantifier and putting the pattern into a variable:

#!/bin/bash
VERSION="1.2.3"
rx='^([0-9]+\.){0,2}(\*|[0-9]+)$'
if [[ $VERSION =~ $rx ]]; then
 echo "INFO:<-->Version $VERSION"
else
 echo "ERROR:<->Unable to validate package version: '$VERSION'"
 exit 1
fi

See the IDEONE demo

The ([0-9]+\.){0,2} parts matches 1 or more digits followed with a literal dot 0, 1, or 2 times.

like image 107
Wiktor Stribiżew Avatar answered Sep 24 '22 06:09

Wiktor Stribiżew