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
Use the --no-verify option to skip git commit hooks, e.g. git commit -m "commit message" --no-verify . When the --no-verify option is used, the pre-commit and commit-msg hooks are bypassed.
If you want to manually run all pre-commit hooks on a repository, run pre-commit run --all-files . To run individual hooks use pre-commit run <hook_id> . The first time pre-commit runs on a file it will automatically download, install, and run the hook.
The hooks are all stored in the hooks subdirectory of the Git directory. In most projects, that's . git/hooks .
By default, hooks are stored in . git/hooks within the project's repository. Git populates this folder with sample scripts that developers can use as a starting point.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With