If you work with multiple Git identities (e.g., company and personal), it’s easy to commit with one account and accidentally push from another. The simple pre-push hook below helps catch that mistake by checking your recent commits against a list of “my accounts.” If it finds overlaps, it blocks the push and shows you the matches.
- Reads a list of your own identities (name + email) from
~/.config/git/hooks/my-accounts. - Scans recent commits in the current repository for author lines (
%an <%ae>). - Normalizes and deduplicates both lists, then computes the intersection.
- If two or more identities overlap, it fails the push (helps catch cross-account mixing).
- If one overlaps, it lets the push proceed but shows the match (useful visibility).
- If none overlap, it prints OK and proceeds.
Why “two or more”? One match may be the normal, intended identity; multiple matches suggest mixed identities in recent commits.
# Create a directory to hold your hooks
mkdir -p ~/.config/git/hooks
# Tell Git to use this directory for all repositories
git config --global core.hooksPath ~/.config/git/hooksSave the script below as:
~/.config/git/hooks/pre-push
Make it executable:
chmod +x ~/.config/git/hooks/pre-pushNote: Be sure the filename and the
chmodtarget both refer topre-push.
Create the file ~/.config/git/hooks/my-accounts with one identity per line, using the format:
Your Name <you@example.com>
Work Name <you@company.com>
-
Add/commit as usual.
-
When you push, Git will run
pre-push:- If it detects multiple overlapping identities, the push stops with an error and shows the offending lines.
- Otherwise, the push proceeds.
- Hook didn’t run? Confirm
git config --global core.hooksPathshows~/.git-hooksand the script is executable. - Wrong file made executable? Ensure you ran
chmod +x ~/.git-hooks/pre-push(notpre-commit). - No accounts file? Create
~/.git-hooks/my-accountswith your identities as shown above.
That’s it! This lightweight guard helps keep your commits aligned with the right identity before they leave your machine.