Search code examples
bashgitgithooksgit-commit

How to make a git pre-commit hook that checks the commit message?


I have a git commit hook script, that checks the commit message, and if the message does not contain the word "updated", the script should reject the commit.

#!/bin/bash
read -p "Enter a commit message: " message

if [[ ${message} != *"updated"* ]];then
  echo "Your commit message must contain the word 'updated'"
  else
  git commit -m "$message"
  fi

How to make this hook automatically execute if I try to push some files in my local repo using the command

git commit -m "updated:something"

My idea is to make it not like "run this script to do commit", but rather when you open the console and try to make a commit and entering the commit message, the script will check your commit message automatically and pass it or reject it.


Solution

  • Taking commit-msg for example.

    #!/bin/bash
    
    MSG="$1"
    
    if ! grep -qE "updated" "$MSG";then
        cat "$MSG"
        echo "Your commit message must contain the word 'updated'"
        exit 1
    fi
    

    chmod 755 commit-msg and copy it as .git/hooks/commit-msg.