The if condition must only be true if the input to script is in the below two format.
QUAL(12345):Some Message
PROD(45678):Some Message
I tried the below code and it works for above but the if condition is becoming true even for non desired/negative scenarios like,
QAULIC(12345):Some Message
PROD34dikek(12345):Some Message.
Please help me out so that this code only work for what it is meant for.
#!/bin/bash
set -x
jiraid=$(echo "$1" | awk -F'[\(\)]' '{print $2}')
if [[ "$1" =~ ^QUAL* ]] || [[ "$1" =~ ^PROD* ]] && [[ $jiraid =~ ^-?[0-9] $ ]]
then
echo "Run Pipeline"
fi
CodePudding user response:
If you only want to match on the string PROD or QUAL immediately followed by parentheses then you need to make that a condition of your regex. ^QUAL*
for example matches anything that starts with QUAL no matter what comes after. If you don't want that then make the regex more specific.
Here's an example of a regex that matches a string starting with QUAL or PROD, immediately followed by a number in parentheses, followed by a colon and a message. If the match is successful then BASH_REMATCH will be populated with the matching string and any capture groups you define (I captured QUAL/PROD, the number, and the message for this example).
#!/bin/bash
regex='^(QUAL|PROD)\((-?[0-9] )\):(.*)$'
test_strings=(
"QUAL(12345):Some Message"
"QUAL(-12345):Some Message"
"QAULIC(12345):Some Message"
"PROD(45678):Some Message"
"PROD34dikek(12345):Some Message."
)
for str in "${test_strings[@]}" ; do
echo "Testing: $str"
[[ $str =~ $regex ]] && declare -p BASH_REMATCH
done
Outputs:
Testing: QUAL(12345):Some Message
declare -ar BASH_REMATCH='([0]="QUAL(12345):Some Message" [1]="QUAL" [2]="12345" [3]="Some Message")'
Testing: QUAL(-12345):Some Message
declare -ar BASH_REMATCH='([0]="QUAL(-12345):Some Message" [1]="QUAL" [2]="-12345" [3]="Some Message")'
Testing: QAULIC(12345):Some Message
Testing: PROD(45678):Some Message
declare -ar BASH_REMATCH='([0]="PROD(45678):Some Message" [1]="PROD" [2]="45678" [3]="Some Message")'
Testing: PROD34dikek(12345):Some Message.