Git Hooks
Scripts that run on commit.
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.

- 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.
#!/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
fiThe 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.
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.
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