You open git log on a Monday morning and suddenly spot a mysterious commit sitting right on main. Alongside it are branches named things like test, fix-this, and johns-code. When it’s time for code review or CI/CD runs, the whole team wastes 30–60 minutes untangling the mess, reverting, and cherry-picking from scratch.
This rarely happens because someone deliberately ignores the workflow. When a deadline is looming, forgetting to switch branches is an easy mistake to make. Branch Protection on GitHub or GitLab only blocks you at git push, meaning you’ve already created a pile of commits on your local machine. A cleaner fix is to catch it right on the developer’s machine using Git Client Hooks written in pure Shell Script—lightweight, with no Node.js or external dependencies required.
My 8-person team used to spend several hours every week just cleaning up junk branches. Since adopting this hook, accidental commits to main have practically disappeared.
Quick start: Set it up in 5 minutes
Follow the 4 steps below to try it out in your repository right away.
Step 1: Create a hooks directory in your repo
Open a terminal at your project root, create a .githooks directory, and point your Git configuration (version 2.9 or later) to it:
mkdir -p .githooks
git config core.hooksPath .githooks
Step 2: Create the pre-commit file
Create .githooks/pre-commit with the following Shell Script to validate branch names:
#!/usr/bin/env bash
# Get the current branch name; skip if in detached HEAD state (e.g., during rebase)
branch=$(git symbolic-ref --short HEAD 2>/dev/null)
if [[ -z "$branch" ]]; then
exit 0
fi
# 1. Block direct commits to main or master
if [[ "$branch" == "main" || "$branch" == "master" ]]; then
echo "❌ Error: Direct commits to the '$branch' branch are not allowed!" >&2
echo "👉 Please create a new branch: git checkout -b feat/feature-name" >&2
exit 1
fi
# 2. Validate branch naming convention
pattern="^(feat|fix|hotfix|chore|docs)/[a-z0-9._-]+$"
if [[ ! "$branch" =~ $pattern ]]; then
echo "❌ Error: Branch name '$branch' does not follow the naming convention!" >&2
echo "👉 Required format: <type>/<short-description>" >&2
echo " Valid examples: feat/login-google, fix/payment-error, chore/update-deps" >&2
exit 1
fi
exit 0
Step 3: Make it executable
On Linux and macOS, the script file needs executable permissions so Git can run it:
chmod +x .githooks/pre-commit
Step 4: Test it out
Try creating a non-compliant branch like test123 and committing a dummy file:
git checkout -b test123
touch demo.txt && git add demo.txt
git commit -m "test hook"
Git will block it immediately and print an error message with instructions in your terminal. No unwanted commits are created.
Deep dive: The problem, the cause, and how Shell Script solves it
Why reminders and documentation aren’t enough
Almost every team has a CONTRIBUTING.md file that defines branch naming rules and forbids committing directly to main. But in a rush, hardly anyone remembers to open the docs and double-check. You end up working on autopilot, and only realize you’re on the wrong branch two or three commits later.
Many developers reach for Husky for convenience, but it requires Node.js. For backend projects using Go, Python, PHP, or Java, forcing the whole team to install Node.js just to run a few lines of Git checks is unnecessarily heavy. Shell Script, on the other hand, is available out of the box on Linux, macOS, and Windows Git Bash, and executes in a fraction of a second.
How Git Client Hooks work
Whenever you run commands like commit, merge, or push, Git looks for a script matching that event name in its hooks directory. Before saving a commit, Git executes the pre-commit file.
- Returns
exit 0: Everything looks good, and Git proceeds to create the commit. - Returns a non-zero code (such as
exit 1): Git aborts the commit immediately, keeping your staged files intact so you can fix the issue.
Breaking down the Shell Script
git symbolic-ref --short HEAD: Returns the short branch name (e.g.,feat/user-profile) instead ofrefs/heads/feat/user-profile. Adding2>/dev/nullsuppresses errors when you’re in a detached HEAD state, and checking-z "$branch"ensures you don’t get blocked during agit rebase.[[ ! "$branch" =~ $pattern ]]: Bash’s built-in regex matching syntax. The pattern^(feat|fix|hotfix|chore|docs)/[a-z0-9._-]+$requires the branch name to start with a valid prefix, followed by a slash and a lowercase description with no spaces.>&2: Redirects error messages to Standard Error (stderr) instead of Standard Output, following standard CLI conventions.
Going further: Sharing hooks with your team and blocking at push
Syncing Git Hooks via a shared directory
By default, Git stores hooks in .git/hooks/. Because the .git directory is never pushed to the remote, teammates who clone the repo won’t get any of your hooks.
That’s why we place the scripts in .githooks/ inside the repository itself and point core.hooksPath there. To let new team members enable everything with a single command, add a setup-hooks.sh script at the project root:
#!/usr/bin/env bash
git config core.hooksPath .githooks
chmod +x .githooks/*
echo "✅ Git hooks enabled for this project!"
Make sure to commit both the .githooks directory and setup-hooks.sh to the repo so everyone shares the same setup.
Adding a pre-push hook as a second line of defense
Occasionally, someone might use the --no-verify flag to bypass the commit hook, or accidentally merge into main locally. In those cases, pre-push acts as a final safeguard before code leaves their machine.
Create .githooks/pre-push and make it executable with chmod +x .githooks/pre-push:
#!/usr/bin/env bash
protected_branches="^(main|master)$"
current_branch=$(git symbolic-ref --short HEAD 2>/dev/null)
if [[ "$current_branch" =~ $protected_branches ]]; then
echo "❌ Push rejected: Cannot push directly from the '$current_branch' branch!" >&2
echo "👉 Please open a Pull Request from a feat/ or fix/ branch." >&2
exit 1
fi
exit 0
Practical tips for adopting this in your project
- Use
--no-verifyjudiciously: In an emergency—like a hotfix for a deployment config or a tricky rebase—you can rungit commit --no-verifyto temporarily skip local hooks. Still, keep Branch Protection enabled on GitHub or GitLab as your server-side safety net. - Keep pre-commit fast: Don’t cram your entire Unit Test suite or Docker build into
pre-commit. Waiting 30 seconds on every commit will make the whole team look for ways to disable the hook. Checking branch names with Shell Script takes under 50ms. - A note for Windows users: Team members on Windows should run Git through Git Bash so a Bash environment is available. Add
*.sh text eol=lfand.githooks/* text eol=lfto your.gitattributesfile to prevent CRLF line endings from breaking the shebang (bad interpreter) on Linux and macOS. - Keep prefixes simple: Sticking to 4–5 familiar prefixes like
feat/,fix/,hotfix/,chore/, anddocs/is plenty. Creating too many categories only slows down new team members trying to pick the right one.

