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.

doughlass
  • 53
  • 4
  • 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`. – M. Nejat Aydin Aug 25 '22 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?"](https://stackoverflow.com/questions/218156/bash-regex-with-quotes) Also, `\d` probably isn't supported (especially inside a bracket expression). – Gordon Davisson Aug 25 '22 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. – Ed Morton Aug 25 '22 at 20:15

1 Answers1

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"
xgord
  • 4,606
  • 6
  • 30
  • 51