How can I create a Git repository with the default branch name other than “master”?

Newer Git, New Repo

Since git version 2.28.0 the git init command now takes a --initial-branch (or -b for short) parameter. These two commands create a new Git repo with a branch named “trunk”, which always made more sense to me than “master” (master of what?):

git init --initial-branch=trunk
git init -b trunk

This is configurable with the init.defaultBranch setting. If I want all new repos to have “trunk” as the default branch:

git config --global init.defaultBranch trunk

Older Git, New Repo

Some systems still have older Git installations. My Debian 10 server (Buster, the current stable version as of October 2020) comes with Git 2.20, which does not support the -b option. One option is to create the repository and then change the branch name. This technique works for normal (non-bare) repos:

git init
git checkout -b trunk

This creates a new repository with trunk as the current branch instead of master. The branch master does not actually exist–the branches don’t get created until they have at least one commit. Until the branch gets created, the branch only exists in .git/HEAD, which explains why the master branch will disappear when you switch to trunk.

Bare Repos

For bare repos, you cannot run git checkout (that’s what it means to be bare). Instead, you can change HEAD to point at a different branch:

git init --bare
git symbolic-ref HEAD refs/heads/trunk

Old Repos

If you’ve already committed, you can run git branch -m instead:

git init
touch file.txt
git add file.txt
git commit -m 'commit 1'
git branch -m trunk

This renames the branch from master to trunk once it’s created.

This does seem a bit clunky since the mechanism is different depending on whether the repository is empty, but it works. You can also approach it as “creating a new branch and deleting master“.

Leave a Comment