繁体   English   中英

git pre-commit hook,将文件添加到索引中

[英]git pre-commit hook, add file into index

我正在尝试编写一个简单的预提交钩子来检查文件是否被修改,如果是这样,压缩它并将其添加到当前索引中,就像这样

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

我有2个问题,1我的情况是失败的,每次,我必须有一个错字或类似的东西,但我不知道它是什么? 这是我回来的错误:

[: 23: git: unexpected operator

而我的第二个问题是,即使我删除了条件,文件也从未实际添加到提交中,它已被修改,但从未添加。

谢谢,狮子座

你的错误是因为你没有引用$mf 将其更改为"$mf" 虽然可能有更好的方法而不是贪图人类可读命令的输出......你可以看一下git status --porcelain例如git status --porcelain 甚至git diff --cached <path> ,然后检查退出代码,例如:

if ! git diff --quiet --cached <path>; then
     # the file was modified; do stuff
fi

我认为Amber可能会误导您:您应该使用--cached ,因为如果未进行更改,那么就此提交而言,没有任何更改,因此我想您不想做任何其他事情。

当然,我不知道您的项目,但是我不确定为什么您要执行这样的操作-通常您不想检入机器生成的内容,只是想轻松地从中重建内容即可入住。

至于你的上一个问题,正在修改但未添加到提交的文件,我无法用玩具示例重现它。 我将其作为预提交挂钩:

#!/bin/bash
touch z
git add z

并进行了提交,并按预期方式创建,添加和提交了z。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM