Changing default branch of git init
With the planned update for Github to start using main
instead of master
for the initial default branch, I started moving all my projects on my personal git server. Until the git project itself updates the tools, initializing new projects locally still is a little bit of pain. With a simple shell script we can automate it.
The HEAD
reference needs to be updated in the project to point to a new branch. To do this we use
$ git symbolic-ref HEAD refs/heads/<new branch name>
This will change the HEAD
pointer to direct to the head of the given branch. On a new repo with no commits, the first commit will default to the HEAD
pointer’s branch. The manual process would be:
$ mkdir /tmp/foo; cd $_ $ git init Initialized empty Git repository in /tmp/foo/.git/ $ git reflog fatal: your current branch 'master' does not have any commits yet $ git symbolic-ref HEAD refs/heads/main $ git reflog fatal: your current branch 'main' does not have any commits yet $
If you’re like me you’ll forget this right away. We can create a shell function that will perform the action on a git init
command. Add the following to your .bashrc
or .zshrc
.
function git() { command git "$@" if [[ $? -eq 0 && "$1" == "init" && "$@" != *"--help"* ]]; then echo "Setting HEAD to branch main" git symbolic-ref HEAD refs/heads/main fi }
The script calls git
with the arguments supplied. If it is successful, is calling git init
and isn’t calling --help
the HEAD
ref is changed to main
.
$ mkdir /tmp/bar; cd $_ $ git init Initialized empty Git repository in /tmp/bar/.git/ Setting HEAD to branch main $ git reflog fatal: your current branch 'main' does not have any commits yet $