Git hooks

Git hooks are scripts that automatically run every time a particular event occurs in a Git repository. They let us customize Git’s internal behavior and trigger customizable actions at key points in the development life cycle.

Hooks reside in the .git/hooks directory of every Git repository. Git automatically populates this directory with example scripts when we initialize a repository.

git hooks

These represent most of the available hooks, but the .sample extension prevents them from executing by default. To “install” a hook, all we have to do is remove the .sample extension. Or, if we are writing a new script from scratch, you can simply add a new file matching one of the above filenames, minus the .sample extension.

Example: Push the commits to the remote repo, automatically after committing the changes in local repo. A post-commit hook in Git allows us to perform actions automatically after a commit is made. If we want to automatically push the code to a remote repository after committing, we can create a post-commit hook script. Here's how we can do it in Git: Step 1: Navigate to the .git/hooks directory of our Git repository. Step 2: Create a new file named post-commit (without any file extension) if it doesn't already exist. Step 3: Open the post-commit file in a text editor and add the following script:

Bash

#!/bin/bash
# Automatically push to the remote repository after a commit
git push origin <branch-name>

Replace <branch-name> with the name of the branch we want to push to (e.g., main, master, develop). Step 4: Save the file and make it executable. We can do this by running the following command in our terminal:

Bash

chmod +x post-commit

Now, every time we make a commit, Git will automatically push the committed changes to the specified branch in the remote repository.