Friday, January 08, 2021

Configuring git to prevent commits of temporary/debug code

Developers, have you ever embarrassingly pushed a commit that inadvertently included temporary debug log/print statements, or other code that you intended to remove before committing? I have!

I wondered if it was possible to add some keyword to a code file -- for example, DONOTCOMMIT -- which, if present, would cause git to automatically reject the commit. This could be added as a comment alongside any temporary debug code, to make it impossible to forget to remove that code before committing.

It turns out that it is possible to do this -- and have it apply automatically to all of your local git repositories -- using a git pre-commit hook.

Quick instructions

(The specifics in these instructions apply to Unix-like filesystems, including Mac OS.)

1. If it doesn't already exist, create the directory: ~/.git_templates/hooks/

2. If it doesn't already exist, in that hooks directory, create a text file named: pre-commit (no extension).

3. Add the following content to the pre-commit file:


FOUND=$(git diff-index --cached -U0 HEAD -- | grep DONOTCOMMIT | wc -l)

if [[ $FOUND -gt 0 ]]; then
    echo "pre-commit hook: DONOTCOMMIT detected, commit not allowed"
    echo "(enforced from: ~/.git_templates/hooks/pre-commit)"
    exit 1

4. To apply that pre-commit hook to all git commit operations on your local machine, from the terminal, run:

git config --global core.hooksPath ~/.git_templates/hooks


Credit to for the pre-commit hook code.

Credit to for the core.hooksPath global git config command.

No comments:

Post a Comment

Hi spammers! No need to waste your time here; comments are heavily moderated, so if you like, you can save us both a little time and just move on to the next site. :-)

For everyone else: Thanks for visiting! Your comments are more than welcome!