user2490003 user2490003 - 2 years ago 142
Git Question

`git diff` does not work when run from a git pre-commit hook

I have a git pre-commit hook that does some style checking on any modified files before committing.

The implementation is irrelevant, but it starts by calling

git diff
. Here's what i have in


echo "=== Running script..."
git diff
echo "=== Done running script..."

# Other stuf
# ....

# Always exit with 1 so pre-commit hook always fails.
# Useful for testing
exit 1

When I actually try committing something, the
hook correctly fires, but the
git diff
command doesn't output anything (there are definitely modified files)

> git commit --all -m "foo"
=== Running script...
=== Done running script...

However if I run the
hook script directly/manually, it does work

> ./.git/hooks/pre-commit
=== Running script...
(... outputs git diff ...)
=== Done running script...

What's different about git calling the hook versus me manually calling it? It runs as the same user either way (my username)

I've also tried suggestions from this thread, but
unset GIT_DIR
, and
didn't fix anything.


Answer Source

You need to use git diff --cached because the changes are already staged.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download