问题
I am trying (but failing miserably) to make a git pre-commit hook that checks for the presence of a var_dump in my modified files and exits if it finds one. The problem that I'm having is that it appears to always be aborting the commit. Here is the contents of my pre-commit file:
VAR=$(git diff | grep -w "var_dump")
if [ -z $VAR ]; then
echo "You've left a var_dump in one of your files! Aborting commit..."
exit 1
fi
回答1:
First of all, note that plain git diff
gives the difference between the working tree and the index (i.e. what can still be staged), not what is about to be committed. Use git diff --cached
to see what is about to be committed.
The second thing I encountered as I was experimenting was that using if [ -z $VAR ]
directly threw an error, because the +
at the beginning of the git diff
output was interpreted by Bash. Make sure to surround $VAR
with quotes to prevent this.
As for the script, you forgot to negate the test if $VAR
is empty. If the output from grep is empty, then "var_dump" was not found, and the hook should return success. The case you want is if it is not empty, meaning "var_dump" was found, and it should abort the commit.
All together:
VAR=$(git diff --cached | grep -w "var_dump")
if [ ! -z "$VAR" ]; then
echo "You've left a var_dump in one of your files! Aborting commit..."
exit 1
fi
来源:https://stackoverflow.com/questions/10840196/aborting-git-pre-commit-hook-when-var-dump-present