WTF are Git hooks?
Learn what Git hooks are and how to automate commits with pre commit hooks in the .git/hooks directory.
Lesson Content
Git hooks are scripts that fire automatically at specific points in your workflow. Want something to happen every time you create a commit? There's a hook for that.
Hooks live in the .git/hooks directory of your project. The naming convention tells you when they run: pre-commit fires before a commit is finalized, post-commit fires after, pre-push fires before pushing upstream, and so on.
To create a hook, just create an executable script that matches the name of one of the sample files, but without the .sample suffix.
Here's a simple pre-commit hook that runs git status before we commit:
.git/hooks/pre-commit
#!/bin/bash
git status
echo ""
read -p "Continue with commit? (y/n) " response < /dev/tty
if [ "$response" != "y" ]; then
echo "Commit aborted."
exit 1
fi
exit 0And don’t forget to make it executable, so it can run when called:
chmod +x .git/hooks/pre-commitNow the git will show me it’s status, and ask me if I want to continue with the commit. If the script exits with a non-zero status, Git aborts the commit.
This is the foundation for automating all kinds of workflows, including code formatting, type-checking, running tests, or triggering external services to run whenever a specific action is carried out.