Create Your First Git hook

Create Your First Git hook

Git hooks are shell scripts found in the hidden .git/hooks directory of a Git repository.

Protect your Git repository from mistakes, automate manual processes, gather data about Git activity, and much more with Git hooks.

There are two groups of these hooks: client-side and server-side. Client-side hooks are triggered by operations such as committing and merging, while server-side hooks run on network operations such as receiving pushed commits. You can use these hooks for all sorts of reasons.

Git hooks are shell scripts found in the hidden .git/hooks directory of a Git repository. These scripts trigger actions in response to specific events, so they can help you automate your development lifecycle. Every Git repository includes 12 sample scripts. Because they're shell scripts, they're extremely flexible, and there are even some Git-specific data you have access to within a Git repository.

Create a Git repository

To get started, create a sample Git repository:

$ mkdir example
$ cd !$
$ git init

Take a look at the .git/hooks directory to see some default scripts:

$ ls -1 .git/hooks/ 
applypatch-msg.sample 
commit-msg.sample
fsmonitor-watchman.sample
post-update.sample
pre-applypatch.sample
pre-commit.sample
pre-merge-commit.sample
prepare-commit-msg.sample
pre-push.sample
pre-rebase.sample
pre-receive.sample
update.sample

You can use man githooks to read about these git hook files

Write a simple Git hook

A simple Git hook trick is to prompt the user for confirmation before they commit something to a branch. Create a new file named .git/hooks/pre-commit and open it in a text editor. Add the following text, which queries Git for a list of the files about to be committed for the current branch name and then enters a while loop until it gets a response from the user:

#!/bin/sh

echo "You are about to commit" $(git diff --cached --name-only --diff-filter=ACM)
echo "to" $(git branch --show-current)

while : ; do
    read -p "Do you really want to do this? [y/n] " RESPONSE < /dev/tty
    case "${RESPONSE}" in
        [Yy]* ) exit 0; break;;
        [Nn]* ) exit 1;;
    esac
done

Give execution permission:

$ chmod +x .git/hooks/pre-commit

And then try it out by creating, adding, and committing a file:

$ echo "hello git hooks" > hello.txt
$ git add hello.txt
$ git commit -m 'but warn me first'
You are about to commit hello.txt
to main
Do you really want to do this? [y/n] y
[main 125993f] but warn me first
 1 files changed, 1 insertion(+)
 create mode 100644 hello.txt

Did you find this article valuable?

Support Shubham Kshetre by becoming a sponsor. Any amount is appreciated!