git pre-commit hook, add file into index

北战南征 提交于 2019-12-30 11:33:51

问题


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? 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


回答1:


Your error is because you're not quoting $mf. Change it to "$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. Or even git diff --cached <path>, and just examine the exit code, e.g.:

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.

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.



来源:https://stackoverflow.com/questions/8470755/git-pre-commit-hook-add-file-into-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!