I've got a variable in my shell script for a git branch name, that might contain a Jira issue key. I want to extract the issue from the variable if it matches my regexp.
A Jira issue can be some letters, followed by a dash, followed by some numbers. My script for this is the following:
#!/bin/bash
echo "pre-receive HOOK"
while read oldrev newrev refname
do
echo "Refname is"
echo $refname //refs/heads/XS-1141
echo "Old revision is"
echo $oldrev
echo "New revision is"
echo $newrev
re="[A-Z] -\d "
echo "checking if branch name contains a JIRA issue (format XX-1111, SRS-1 or similar)"
if [[ $refname =~ $re ]]; then echo ${BASH_REMATCH[1]}; fi;
done
My input is in the comment there in the script (refs/heads/XS-1141) and the output of that is the BASH_REMATCH empty.
I'd like to achieve two things here:
- Find out if the branch name contains a Jira issue
- Extract that Jira issue to a variable
How can I do that?
CodePudding user response:
Your re has no groups, so you need to use ${BASH_REMATCH[0]}
Also, you need to replace \d
with [0-9]
as \d
digit matching pattern is not supported by POSIX ERE.
So you can use
#!/bin/bash
refname='refs/heads/XS-1141'
re="[A-Z] -[0-9] "
echo "checking if branch name contains a JIRA issue (format XX-1111, SRS-1 or similar)"
if [[ $refname =~ $re ]]; then echo ${BASH_REMATCH[0]}; fi;
See the online demo.
The ${BASH_REMATCH[0]}
holds the XS-1141
value here.