Git Pre-commit Hook to Block Debug Code

This pre-commit hook checks the staged changes, and blocks the commit if it finds var_dump( or console.log(. It stops debug code going to the repository by mistake.

#!/bin/sh
# Block commit if staged lines contain debug code

PATTERN='var_dump\(|console\.log\('

if git diff --cached -U0 | grep -E "^\+.*($PATTERN)" > /dev/null; then
  echo "Commit blocked: remove debug code (var_dump / console.log)."
  git diff --cached -U0 | grep -E "^\+.*($PATTERN)"
  exit 1
fi

exit 0
Terminal output

$ chmod +x .git/hooks/pre-commit
$ echo 'console.log("test");' > app.js
$ git add app.js
$ git commit -m "Add app"
Commit blocked: remove debug code (var_dump / console.log).
+console.log("test");
$ echo 'alert("hello");' > app.js
$ git add app.js
$ git commit -m "Add app"
[main (root-commit) 7c5a852] Add app
1 file changed, 1 insertion(+)
create mode 100644 app.js

How it works

  • git diff --cached -U0 shows only the staged changed lines.
  • grep -E "^\+.*(pattern)" looks for added lines (they start with a plus) which have the debug function.
  • A non zero exit (exit 1) stops the commit. In the second try, the file is clean and the commit works.
Note: You can skip a hook once with git commit --no-verify, but do it only in a real emergency. See Git Hooks.

Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.