Git pre-commit hook, add file to index

I'm trying to write a simple pre-commit bind to check if a file has been modified, if so, compress it and add it to 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 questions, 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 am returning:

[: 23: git: unexpected operator

      

And my second problem is that even if I remove the condition, the file will never be added to the commit, it will be modified but never ADDED.

Thanks Leo

+1


source to share


1 answer


Your error is due to the fact that you are not quoting $mf

. Change it to "$mf"

. Although there are arguably more efficient ways than grepping the output of the command for human readability. For example, you can take a look at git status --porcelain

. Or even git diff --cached <path>

, and just check the exit code like:

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 no changes are delivered, then as far as that is related, there is no change, 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 are doing something like this - usually you don't want to check machine generated content, just make it easy to rebuild from what is checked.



Regarding your last issue, the file is modified but not added to the commit, I cannot reproduce it with the toy example. I did it as a pre-commit hook:

#!/bin/bash
touch z
git add z

      

and did a commit, and z was created, added and committed.

+3


source







All Articles