Change git init default branch name

As of Git 2.28 (released 27th July 2020), you can now configure the name of the branch created when you init a new repository:

$ git config --global init.defaultBranch main

After setting this variable, running git init will produce a repository whose initial branch is main:

$ git init
Initialised empty Git repository in /home/thomas/test-git-repo/.git/
$ git status
On branch main

No commits yet

nothing to commit (create/copy files and use "git add" to track)

Release notes: https://lore.kernel.org/git/[email protected]/


HEAD is hardcoded in git to point to refs/heads/master.

if (create_symref("HEAD", "refs/heads/master", NULL) < 0)

So there is no config setting or option that you can pass to git init to change it to something else.

What is possible though is to change what HEAD points to right after git init with the help of git symbolic-ref:

$ git init
$ git symbolic-ref HEAD refs/heads/test

This will change HEAD to point to a (not yet existing) branch called test. Then when you create your first commit, the branch will be called test instead of master.


A simple way to change the default HEAD is to create a HEAD in the git template dir. First, configure your template dir to ~/Templates/git.git (or whatever you'd prefer):

$ git config --global init.templateDir '~/Templates/git.git'
$ cp -r /usr/share/git-core/templates ~/Templates/git.git

Then, create the file HEAD in the template dir:

$ echo 'ref: refs/heads/default' > ~/Templates/git.git/HEAD

And you're good to go! Whenever you run git init, you'll now get the message:

$ git init
Reinitialized existing Git repository in [...]

For some reason, git decides whether to use this message based on the presence of the HEAD file in .git, rather than relying on whether or not .git had to be created. However, it really doesn't matter what message it shows you. From the git-init man page:

Running git init in an existing repository is safe. It will not overwrite things that are already there. The primary reason for rerunning git init is to pick up newly added templates (or to move the repository to another place if --separate-git-dir is given).

That is to say, git init is guaranteed not to overwrite the HEAD you put in the template, and it won't use the template's HEAD to overwrite an existing HEAD either. Since this is explicitly documented, you can rely on it.

Additionally, it also says:

Files and directories in the template directory whose name do not start with a dot will be copied to the $GIT_DIR after it is created.

Which means you can also rely on the template being copied immediately after the creation of .git, and not at a later point.

(Of course, this is my personal interpretation of the manual. It's entirely possible that the git developers will disagree.)

Tags:

Git