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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With