0

I have the following regex pattern I'd like to use to validate git commit messages. (((CMS-)|(UIDEV-)|(CONTENT-)|(RPT-))[0-9]+\\s-\\s)|(NOTICKET- )

However when I have a sample message of CMS-7120 - test commit message, the regex match fails and enter the if condition. I used to have \\d+ but realized that wasn't POSIX compliant and changed it above but unsure why I'm not getting a match. Tested it on regex101 and I do get a match there. Any thoughts on what is wrong here?

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

pattern="(((CMS-)|(UIDEV-)|(CONTENT-)|(RPT-))[0-9]+\\s-\\s)|(NOTICKET- )"
message="$(cat $1)"

if [[ !($message =~ $pattern) ]]; then
    echo "bad commit message"
    exit 1
fi
uioporqwerty
  • 1,068
  • 3
  • 12
  • 30
  • 1
    `\s` is a PCRE extension. Bash only guarantees support for ERE regex syntax (extensions beyond that are specific to the libc it was compiled against, thus to your operating system). – Charles Duffy May 29 '22 at 17:23
  • Use `[[:space:]]` instead. – Charles Duffy May 29 '22 at 17:24
  • 3
    Also, you can't reliably use `sh` in your shebang line with bash-only syntax. Use `#!/usr/bin/env bash`, not `#!/usr/bin/env sh`. – Charles Duffy May 29 '22 at 17:24
  • 3
    And spaces are important. `if ! [[ $message =~ $pattern ]]` is better practice, or if you _must_ have the parens, `if [[ ! ( $message =~ $pattern ) ]]` – Charles Duffy May 29 '22 at 17:25
  • 2
    See https://ideone.com/MYRrjk showing code working after being modified as described above. – Charles Duffy May 29 '22 at 17:32
  • ...and btw, consider `message=$(<"$1")` to avoid the overhead of starting `cat`. – Charles Duffy May 29 '22 at 17:33
  • 2
    (and think about using single-quotes instead of double-quotes by default -- with single quotes you don't need to double up your backslashes; and more generally, because there's less processing inside them, using them lets a reader know that your substring is literal). – Charles Duffy May 29 '22 at 17:34
  • Thanks @CharlesDuffy. That solved it and I learned more about bash. – uioporqwerty May 29 '22 at 17:38

0 Answers0