6

i wrote the following script. It will be used in a build process later. My goal is to decide whether it's a pre release or a release. To archive this i compare $release to a RegEx. If my RegEx matches it's a pre release, if not it's a release.

#/bin/bash
release="1.9.2-alpha1"
echo "$release"
if [[ "$release" =~ \d+\.\d+\.\d+[-]+.* ]];then
echo "Pre"
else
echo "Release"
fi

But as result i always end up with the following:

~$ bash releasescript.sh
1.9.2-alpha1
Release

Version:

Ubuntu 18.04.1 LTS

I used this editor to test my RegEx. I'm stuck for at least 6h, so i would appreciate some help greatly.

New contributor
venter is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
11

\d and \w don't work in POSIX regular expressions, you could use [[:digit:]] though

#/bin/bash
release="1.9.2-alpha1"
echo "$release"
LANG=C # This needed only if script will be used in locales where digits not 0-9
if [[ "$release" =~ ^[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+-+ ]];then
echo "Pre"
else
echo "Release"
fi

I have tested this script, it output "Pre" for given $release

Checked out your regex builder, it works only with perl compatible and javascript regex, while you need posix, or posix extended.

By @dessert:

[0-9] is the shorter alternative to [[:digit:]]. As the beginning of the string is to be matched, one should add ^, while .* at the end is superfluous: ^[0-9]+\.[0-9]+\.[0-9]+-+ – using a group this can be further shortened to: ^([0-9]+\.){2}[0-9]+-+

  • 3
    Beat me to it! Also, fwiw if you'd used shellcheck then it has a warning "SC1001: This \d will be a regular 'd' in this context.", which is quite helpful. Other answers. – pbhj May 16 at 10:45
  • 2
    Is [0-9] equivalent to [[:digit:]] though? I was under the impression that POSIX character classes match Unicode characters, so could very well match digits in languages that don't use 0-9. – Fax May 16 at 12:38
  • @Fax Not sure about [0-9] but [A-Z] match unicode characters, the way to change that is only set locale by LANG=C – LeonidMew May 16 at 12:46
  • 1
    @Fax "Is [0-9] equivalent to [[:digit:]] though?" TIL that the answer is no. – levant pied May 16 at 20:25

Your Answer

venter is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.