bash 如何捕获 git commit 消息并运行操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4870007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:22:54  来源:igfitidea点击:

How to capture a git commit message and run an action

gitbashgithooks

提问by James Nine

I'm new to git and I want to be able to capture the commit message after a push to the origin/master and run a bash script (on the server) based on what the string contains.

我是 git 的新手,我希望能够在推送到原点/主站后捕获提交消息,并根据字符串包含的内容运行 bash 脚本(在服务器上)。

For example, if my git commit message says: [email] my commit message

例如,如果我的 git commit 消息说: [email] my commit message

If the commit message contains [email]then do a specified action, otherwise, don't do it.

如果提交消息包含[email]则执行指定的操作,否则不执行。

Here's a sample bash script I'm thinking of using in the post-receivehook:

这是我想在post-receive钩子中使用的示例 bash 脚本:

#!/bin/bash

MESSAGE= #commit message variable?

if [[ "$MESSAGE" == *[email]* ]]; then
        echo "do action here"
else
        echo "do nothing"
fi

Basically all I need to know is what the variable name for the commit message is, to use in the above bash script? Also, I'm not sure if this is the right hook to do this or not.

基本上我需要知道的是提交消息的变量名称是什么,在上面的 bash 脚本中使用?另外,我不确定这是否是执行此操作的正确方法。

回答by James Nine

I think I figured out the answer to my own question; the variable can be obtained using the git-logcommand:

我想我找到了自己问题的答案;可以使用以下git-log命令获取变量:

git log -1 HEAD --pretty=format:%s

so, my script would be:

所以,我的脚本是:

#!/bin/bash

MESSAGE=$(git log -1 HEAD --pretty=format:%s)

if [[ "$MESSAGE" == *\[email\]* ]]; then
        echo "do action here"
else
        echo "do nothing"
fi

I hope this might help anyone else who is searching for the answer.

我希望这可以帮助其他正在寻找答案的人。

回答by Pablo Fernandez

You probably want a git hookfor that

你可能需要一个混帐挂钩