2

In Bash I'm trying to check if a string is in the appropriate format.

#!/bin/bash

COMMIT_MSG="release/patch/JIRA-123"

[[ $COMMIT_MSG =~ 'release\/(major|minor|patch)\/[A-Z\d]+-\d+' ]] && echo "yes" || echo "no"

This is the regex I've used to match the string as patch could be either major or minor and JIRA-123 is Jira Ticket ID but when trying it in the Bash regex it always returns no.

3
  • 1
    Use [[ $COMMIT_MSG =~ release/(major|minor|patch)/[A-Z0-9]+-[0-9]+ ]] . Don't quote the regex and use 0-9 instead of \d. Commented Aug 25, 2022 at 19:16
  • 3
    Quoting the pattern makes bash treat it as a literal string, rather than regex syntax. Actually, to avoid inconsistencies between bash versions, it's best to store the pattern in a variable, then use that (unquoted) in the actual test. See "bash regex with quotes?" Also, \d probably isn't supported (especially inside a bracket expression). Commented Aug 25, 2022 at 19:18
  • 2
    Note that condition && action1 || action2 in bash is not a ternary expression so be careful when treating it as one - as written you could get no output even if your regexp comparison succeeded. Whether or not you care probably depends on how likely you think it is that echo "yes" might fail. Commented Aug 25, 2022 at 20:15

1 Answer 1

6

Bash is a simplified version of regex called "Extended Regular Expression". \d doesn't exist in it, so use [0-9] instead.

Additionally, you shouldn't quote the regex in the condition.

[[ $COMMIT_MSG =~ release/(major|minor|patch)/[A-Z0-9]+-[0-9]+ ]] && echo "yes" || echo "no"
Sign up to request clarification or add additional context in comments.

Comments

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.