Git and libgit2

The First Git Branch Is Created Lazily

Published 2023-03-10. Last modified 2023-03-11.
Time to read: 1 minutes.

This page is part of the git collection.

If you intend to type along, you might want to read about selectively disabling the git pager first.

Creating Branches

Git branches do not exist, and cannot be created, before the initial commit.

Shell
$ mkdir ~/test && cd ~/test
$ git init Initialized empty Git repository in /home/mslinn/test/.git/

Typing git status in a new repo will report that the current branch is master. This is misleading.

Shell
$ git status
On branch master
No commits yet
nothing to commit (create/copy files and use "git add" to track)

The default branch name for new git installations is master, however it is only created when the initial commit is made. If you list the git branches, before the initial commit you will see no branches actually exist yet:

Shell
$ git branch -l # no output is generated because no branches exist yet 

As readers of this blog probably know, git provides two equivalent commands that create a new branch:

  1. git branch new_branch_name
  2. git checkout -b new_branch_name

You may be surprised to learn that the new branch is not actually created until the first commit.

Shell
$ git branch new_branch_name
$ git branch -l # no output is generated because no branches exist yet

Taken together, this means that if you run git branch new_branch_name on an empty git repository, you are just renaming the primary branch for that git repository, and that branch will not be created until the first commit. This is why the first branch in a git repository is said to be lazily created.

Thus, you can run git branch new_branch_name several times before the first commit, and all incantations but the last will have no effect.

Shell
$ git branch my_new_branch_1
Switched to a new branch 'my_new_branch_1' 
$ git branch my_new_branch_2 Switched to a new branch 'my_new_branch_2'
$ git branch my_new_branch_3 Switched to a new branch 'my_new_branch_3'
$ git branch -l # no branches are listed
$ touch blah
$ git add blah
$ git commit -m - [my_new_branch_3 (root-commit) 8227ede] - 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 blah
$ git branch -l my_new_branch_3

To configure the initial branch name for use in all new repositories, set the init.defaultBranch global git configuration value. For example, to set master as the initial branch name, type:

Shell
$ git config --global init.defaultBranch master
* indicates a required field.

Please select the following to receive Mike Slinn’s newsletter:

You can unsubscribe at any time by clicking the link in the footer of emails.

Mike Slinn uses Mailchimp as his marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp’s privacy practices.