Home > front end >  Get commit message in Git hooks
Get commit message in Git hooks

Time:09-13

I would like to create commit-msg hook to check the commit message with some regex. So I wrote this bash script in the hooks folder:

#!/bin/sh

valid_commit_msg_regex="^[0-9] :[a-zA-Z0-9-_ ]{20,150}$"

message="This commit violates the commit message rules. Please rename your commit."

if [[ ! $(cat $1) =~ $valid_commit_msg_regex ]]
then
    echo "$message"
    exit 1
fi

exit 0

But when I try to write git commit -m "9: texttexttexttexttexttexttexttext" it doesn't work properly and I get the error message from script.
Does anyone has an idea what's gone wrong?

CodePudding user response:

I see two issues:

  • Double brackets [[ comes from bash. Change shebang to #!/bin/bash
  • in [a-zA-Z0-9-_ ] you have to escape - with \-
  • Related