[英]git pre-commit hook, add file into index
I'm trying to write a simple pre-commit hook to check if a file was modified, if so, compress it and add it into the current index, something like this 我正在尝试编写一个简单的预提交钩子来检查文件是否被修改,如果是这样,压缩它并将其添加到当前索引中,就像这样
#!/bin/sh
# was the file modified?
mf='git status | grep jquery.detectBrowser.js'
# is the non-compressed file in the staging area?
if [ $mf != "" ]
then
# alert the user
echo "Javascript file modified, YUI Compressor will begin now."
# go to rhino
cd $HOME/apps/rhino/yuicompressor-2.4.7/build
# compress my file
java -jar yuicompressor-2.4.7.jar ~/www/jquery.detectBrowser.js/jquery.detectBrowser.js -o ~/www/jquery.detectBrowser.js/jquery.detectBrowser.min.js
# comeback to the initial directory
cd -
# add the new file into the index
git add ~/www/jquery.detectBrowser.js/jquery.detectBrowser.min.js
fi
I have 2 issues, 1 my condition is failing, every time, I must have a typo or something like that, but I can't figure out what it is? 我有2个问题,1我的情况是失败的,每次,我必须有一个错字或类似的东西,但我不知道它是什么? This is the error I get back:
这是我回来的错误:
[: 23: git: unexpected operator
And my second problem is that even if I remove the condition the file is never actually ADDED into the commit, it's modified, but never ADDED. 而我的第二个问题是,即使我删除了条件,文件也从未实际添加到提交中,它已被修改,但从未添加。
Thanks, Leo 谢谢,狮子座
Your error is because you're not quoting $mf
. 你的错误是因为你没有引用
$mf
。 Change it to "$mf"
. 将其更改为
"$mf"
。 Though there are perhaps better ways than grepping the output of a human-readable command... you could have a look at git status --porcelain
for example. 虽然可能有更好的方法而不是贪图人类可读命令的输出......你可以看一下
git status --porcelain
例如git status --porcelain
。 Or even git diff --cached <path>
, and just examine the exit code, eg: 甚至
git diff --cached <path>
,然后检查退出代码,例如:
if ! git diff --quiet --cached <path>; then
# the file was modified; do stuff
fi
I think Amber may have misled you: you should use --cached
, because if the changes are not staged, then as far as this commit is concerned, there are no changes, so I assume you don't want to do anything else. 我认为Amber可能会误导您:您应该使用
--cached
,因为如果未进行更改,那么就此提交而言,没有任何更改,因此我想您不想做任何其他事情。
And of course, I don't know your project, but I'm not sure why you're doing something like this - usually you don't want to check in machine-generated content, just make it easy to rebuild from what is checked in. 当然,我不知道您的项目,但是我不确定为什么您要执行这样的操作-通常您不想检入机器生成的内容,只是想轻松地从中重建内容即可入住。
As for your last problem, the file being modified but not added to the commit, I can't reproduce it with a toy example. 至于你的上一个问题,正在修改但未添加到提交的文件,我无法用玩具示例重现它。 I made this as a pre-commit hook:
我将其作为预提交挂钩:
#!/bin/bash
touch z
git add z
and made a commit, and z was as expected created, added, and committed. 并进行了提交,并按预期方式创建,添加和提交了z。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.