
How to Include Githooks in a Repository to Share With Your Team
- 2026-05-04
- 3 minutes to read
Table of Contents
Introduction
Git hooks are scripts that Git executes before or after specific events, such as committing code or pushing to a repository. They can be used to automate tasks, enforce coding standards, or prevent specific actions. However, by default, Git hooks are stored in the .git/hooks directory of each developer’s local repository and are therefore not shared. This means that if you want to use the same hooks across your team, you need to instruct each developer to set up hooks manually, which can lead to inconsistencies and drift. In this post, we will explore a method to include Git hooks in a repository so that they can be easily shared with your team.
Creating a Shared Hooks Directory
The first step is to configure Git to use a directory outside of the .git directory for hooks. We can add the core.hooksPath property to the repository’s Git configuration to specify a custom hooks directory. You can do this from the command line or by exposing the .git folder in VSCode and editing the config file directly. The following command will create a new directory called .githooks in the root of your repository and set it as the hooks path:
# create a directory for shared hooks
mkdir .githooks
# set the hooksPath to the new directory
git config core.hooksPath .githooks
Your gitconfig file should now include the following entry:
[core]
hooksPath = .githooks
Adding Hooks to the Shared Directory
Now that we have a shared hooks directory, we can add our hook scripts to this directory. For example, if you want to add a pre-commit hook, you would create a file named pre-commit in the .githooks directory and add your script to it. Create the file and add the following content to it:
#!/bin/bash
branch="$(git rev-parse --abbrev-ref HEAD)"
if [ "$branch" = "master" ] || [ "$branch" = "main" ]; then
echo "You can't commit directly to $branch branch"
exit 1
fi
This script will prevent developers from committing directly to the master or main branch, which is a common practice to enforce code review processes. Finally, we need to make the script executable:
chmod +x .githooks/pre-commit
Testing the Shared Hooks
With everything set up, you can now test the shared hooks by trying to commit directly to the main branch. You should see the message “You can’t commit directly to master/main branch” and the commit will be blocked. This setup ensures that all developers on your team will have the same hooks and will be subject to the same rules, improving consistency and collaboration.
References
#mtfbwy
Comments