如何制作一个 git 预提交挂钩来检查提交消息?

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

我有一个 git 提交挂钩脚本,它检查提交消息,如果消息不包含单词 "updated",脚本应该拒绝提交。

#!/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

如果我尝试使用命令将一些文件推送到我的本地存储库中,如何让这个挂钩自动执行

git commit -m "updated:something"

我的想法是让它不像"run this script to do commit",而是当你打开控制台并尝试提交并输入提交消息时,脚本会自动检查你的提交消息并传递它或拒绝它。

commit-msg为例

#!/bin/bash

MSG=""

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

chmod 755 commit-msg 并将其复制为 .git/hooks/commit-msg.