Search code examples
regexbashhusky

Regex not working in bash (MacOS) when trying to validate commit message with husky


I tried to write the next regex for checking GIT commit message with husky

My script:

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

message="$(cat $1)"
if ! [[ $message =~ ^\[.*?\] (resolved|fixed) \#([0-9])* ([A-Z])\w.*$ ]];
then
  echo "🚨 Wrong commit message! 😕"
  echo "[POLICY] Your message is not formatted correctly!"  
  echo "Message format must be like:"  
  echo "[Tag] resolved #123 Case title (for features)"
  echo "[Tag] fixed #123 Case title    (for bugs)"
  echo "First letter of 'Case title' must be capitalized!"  
  exit 1  
fi

Messages should pass: [Tag] resolved #123 Case title (for features) [Tag] fixed #123 Case title (for bugs)

Error occurs: .husky/commit-msg: line 5: syntax error in conditional expression: unexpected token ('`


Solution

  • You can use define the regex as

    rx='^\[[^][]*] (resolved|fixed) #[0-9]* [A-Z][[:alnum:]_].*'
    

    Then, you can use

    if ! [[ "$message" =~ $rx ]];
    

    Note:

    • In a POSIX ERE regex, *? is not parsed as a lazy quantifier, thus [^][]* is used to match any zero or more chars other than [ and ]
    • \w is not universally supported, thus it is better defined as [[:alnum:]_]
    • It is safer to declare the regex as a variable inside single quotes to avoid special char expansion by Bash inside the unquoted pattern.