0

I have this script:

#!/bin/bash
a=`git rev-parse --abbrev-ref HEAD`
echo $a
if [[ "$a" =~ release* ]]; then
    echo "not valid branch allowed to be created"
    exit 1
fi

What I am trying to achieve is that only if the value of a starts with the string release, then the script should exit with status 1.

I want to make sure I validate the value of a against a regex that always starts with the string release and can have any other characters or numbers or special characters after that. However, I see in the script that if a includes the string release anywhere in its value, the script still matches it with the regex and prints the value under the echo.

How do I get the regex right here?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Ashley
  • 1,447
  • 3
  • 26
  • 52

2 Answers2

2

You need to anchor the RE to only match at the beginning of the string. You also don't want that * at the end; it means match 0 or more of the previous thing, in this case an e.

[[ "$a" =~ ^release ]]

You could also use a glob pattern instead of a regular expression:

[[ "$a" = release* ]]
Shawn
  • 47,241
  • 3
  • 26
  • 60
0

I'm not very familiar with Bash regular expression support but this post may help and has some other best practice tips.

Aside, don't you need a caret to match the start of the string? Also, any subsequent characters is period asterisk (i.e. period being any one character, asterisk being zero or more of the previous character).

    ^release.*
David Cross
  • 96
  • 1
  • 3