git pre-commit hook, add file into index

前端 未结 1 1772
悲哀的现实
悲哀的现实 2021-01-16 02:33

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

#!/b         


        
相关标签:
1条回答
  • 2021-01-16 03:25

    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.

    0 讨论(0)
提交回复
热议问题