1

I need bash to check whether CI_COMMIT_REF_NAME matches either the string master, or a three part version number like 1.3.5, 1.1.11 and so on.

Here's what I tried:

#!/bin/bash
CI_COMMIT_REF_NAME=1.1.4
if [ $CI_COMMIT_REF_NAME == 'master' ] || [[ $CI_COMMIT_REF_NAME =~ ^([0-9]{1,2}\.){2}[0-9]{1,2}$ ]]
 then 
     echo "true"
 else 
     echo "false"
fi

The expected output is true, but I get false. Setting the variable to master works as intended, so the mistake must be my regex.

What am I doing wrong?

2 Answers 2

2

You need to declare the regex as a separate variable inside single quotes, there will be no issues parsing your regex in bash then and make sure the parentheses are placed around the [0-9]{1,2}\. part:

rx='^([0-9]{1,2}\.){2}[0-9]{1,2}$'
if [ $CI_COMMIT_REF_NAME == 'master' ] || [[ $CI_COMMIT_REF_NAME =~ $rx ]]

See the online Bash demo

Now, the pattern matches:

  • ^ - start of string
  • ([0-9]{1,2}\.){2} - 2 occurrences of 1 or 2 digits followed with a literal dot
  • [0-9]{1,2} - 1 or 2 digits
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

2 Comments

I added the pattern description. And yes, the parentheses should enclose only the pattern you need to quantify.
Thanks for your help!
2

You probably don't want to match the beginning of the line twice:

$ CI_COMMIT_REF_NAME=1.1.4
$ [[ $CI_COMMIT_REF_NAME =~ (^[0-9]{1,2}\.){2}[0-9]{1,2}$ ]] && echo match
$ [[ $CI_COMMIT_REF_NAME =~ ^([0-9]{1,2}\.){2}[0-9]{1,2}$ ]] && echo match
match

1 Comment

So there were actually two mistakes. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.