Admins eHow SysAdmin Tips & Tricks

April 24, 2025

Adding a Post-Push Hook to Git with the Reference-Transaction Hook

Filed under: Git — Tags: , , , — admin @ 10:18 am

Git doesn’t provide a built-in post-push hook, but you can achieve the same functionality by leveraging the reference-transaction hook. This hook runs during reference updates, such as when you push changes to a remote repository. With a bit of scripting, you can trigger a custom post-push script after a successful push. Here’s how to set it up.

Step 1: Create the reference-transaction Hook

In your repository, navigate to the .git/hooks directory and create or edit the reference-transaction hook file. Add the following script:

#!/bin/bash
set -eu

while read oldvalue newvalue refname
do
    if [ "$1" = "committed" -a "$refname" = "refs/remotes/origin/main" ]
    then
        exec .git/hooks/post-push
    fi
done

What Does This Script Do?

  • set -eu: Ensures the script exits on errors (-e) and treats unset variables as errors (-u) for robustness.
  • while read oldvalue newvalue refname: Reads input from Git about reference updates (old commit hash, new commit hash, and reference name).
  • if [ “$1” = “committed” -a “$refname” = “refs/remotes/origin/main” ]: Checks if the transaction is a committed push to the main branch of the origin remote.
  • exec .git/hooks/post-push: Runs the post-push script if the conditions are met.

Step 2: Create the post-push Hook

Create a file named post-push in the .git/hooks directory and add your desired commands. For example:

#!/bin/bash
echo "Push to origin/main completed successfully!"
# Add your custom post-push actions here

Make sure both scripts are executable:

chmod +x .git/hooks/reference-transaction
chmod +x .git/hooks/post-push

Why Use This Approach?

  • This setup allows you to automate tasks after a push, such as sending notifications, triggering CI/CD pipelines, or logging push events. By tying the hook to refs/remotes/origin/main, you ensure it only runs for pushes to the main branch, keeping your workflow targeted.
    Notes
    The reference-transaction hook is powerful but requires careful scripting to avoid unintended behavior. Test thoroughly in a non-critical repository first.
  • If you need to support other branches or remotes, modify the refname condition in the script accordingly.
  • Credit to this Stack Overflow answer for inspiring this approach.
  • With this setup, you can extend Git’s functionality to suit your workflow, making post-push automation a breeze!

Powered by WordPress