Renaming the git default branch from master to main

By Eric Lathrop on

Since most places are renaming the default git branch from master to main I want to do the same to reduce friction. I want to rename all my default branches in all my projects in one afternoon so I can retrain my muscle memory and not have to remember which project uses which branch name.

I host most of my work on gitlab.com, which protects the default branch from changes/deletion. This means that in addition to running some terminal commands, you need to visit the repositories web site to change some settings. I made a short bash script to make this as quick as possible:

#!/bin/bash
set -e

git branch -m master main
git push -u origin main

# FIXME: only works for gitlab
origin=$(git remote get-url origin | sed -e 's/^.*@//' -e 's/\.git$//' -e 's/:/\//')
xdg-open "https://$origin/-/settings/repository#js-protected-branches-settings"

cat << EOL
Complete the following steps in your browser:
1. Set the default branch to 'main'
2. Protect the 'main' branch
3. Un-protect the 'master' branch

Press <ENTER> when complete
EOL
read

git push origin --delete master

Another related problem is that running git init will still create a repository with a default master branch. If you're on Ubuntu 20.04 LTS, you'll need a newer git. You can install this Ubuntu Git Maintainers PPA to get the most recent git version. Once that's done you can run this command to set your default branch to main:

git config --global init.defaultBranch main

Now I just have to grep $HOME for master and fix any shell scripts or web links.