AI Hints
Home›Git & GitHub Tutorial›Tools and Hooks
Git & GitHub · Lesson 113 of 144

Git Hooks

Scripts that run on commit.

⏱ 2 min read▶ Video at 2:03:45🎓 Free
Watch this lesson in the Git & GitHub courseWatch on YouTube ↗Full Git & GitHub course

Git can run your own scripts automatically, at certain moments, like just before a commit. These scripts are called hooks. They're great for catching mistakes before they're saved.

Git Hooks
From the video: Git Hooks
  • Scripts Git runs for you
  • At moments like 'before commit'
  • Catch mistakes early

A pre-commit hook

This hook lives in dot git slash hooks slash pre commit. Git runs it before every commit. It looks at the staged changes. If any line contains the word debug, it prints a message, and exits with one, which means stop. Git then cancels the commit.

.git/hooks/pre-commitpython
#!/bin/sh
# Stop the commit if a staged file contains "DEBUG"
if git diff --cached | grep -q "DEBUG"; then
  echo "Commit blocked: remove DEBUG lines first."
  exit 1
fi

The hook in action

We make the hook executable, with chmod plus x. Now we stage a line that says debug, and try to commit. The hook blocks it, and prints our message. Remove the line, and the commit goes through.

git
chmod +x .git/hooks/pre-commit
echo '<!-- DEBUG: test -->' >> index.html
git commit -am "Update home page"
Commit blocked: remove DEBUG lines first.
git restore index.html
echo '<p>Hello!</p>' >> index.html
git commit -am "Say hello"
[main 016e849] Say hello
 1 file changed, 1 insertion(+)

Sharing hooks

Hooks inside dot git aren't shared when you push, so each person has to set them up. Teams often use a tool, like pre commit, or husky, to install the same hooks for everyone. And on GitHub, Actions does the same kind of checking for the whole team.

Local only.git/hooks isn't pushed
pre-commit, huskyshare hooks
Actionschecks on GitHub
Bothcatch mistakes early

Summary

Hooks are scripts Git runs at moments like before a commit. A failing pre commit hook stops the commit. Next, a tour of your Git settings.

Key takeaways
  • .git/hooks/pre-commit
  • exit 1 stops the commit
  • Share with tools like husky
Next up: Your Git Settings — the .gitconfig file