Don't commit to main

Tired of accidentally committing to main, only to notice your mistake when your push to remote is rejected? Here's a trick that uses a pre-commit git hook to make sure you'll never commit to main - or other forbidden branches of your choosing - again.

Use a git pre-commit hook

A pre-commit git hook is a script inside a repo's .git/ directory that is triggered before any git commit is executed. When the branch is a protected one (typically main), the commit is refused, and you will save yourself the trouble of undoing the unwanted commit. The hook looks like this:
#!/bin/bash 
 
current_branch="$(git rev-parse --abbrev-ref HEAD)" 
 
# list of branches you shouldn't commit to directly 
forbidden_branches=("main" "production" "some_other_forbidden_branch") 
 
if [[ " ${forbidden_branches[*]} " =~ " ${current_branch} " ]]; then 
  echo "No committing to branch '${current_branch}' please." 
  exit 1 
fi 

Setting the hook up for one repo

To enable the hook for one repo, create or update the pre-commit hook for this repo with the code above.
 $ nano <repo-root>/.git/hooks/pre-commit 
The script has to be executable:
 $ chmod +x <repo-root>/.git/hooks/pre-commit 


Applying the hook everywhere

In case you like this hook, you will want to use it in every repository. For this, create a directory ~/.git-template/hooks and put the git hook in there and make it executable. Now make this your default git template source by running:
 $ git config --global init.templatedir '~/.git-template' 
From now on, each newly cloned repo will have this hook configured by default. For existing repos, you can run git init in the root of that repo. This command will copy the hooks from your template directory, but won't otherwise change the existing configuration of that repo.


related blogs: