Search code examples
gitgit-branch

Why can't I rename master before making a first commit?


I stumbled upon the following error when trying to rename my master branch (git branch -M main):"

error: refname refs/heads/master not found

After making my first commit, I was able to rename my branch without any issues. At this point, I wondered why I couldn't rename the master branch.

The error message suggests that there is no reference "master". This is logical because there are no commits for it to point to. However, it's worth noting that the branch "master" itself exists, as demonstrated by the fact that I can run "git branch --show-current".

So what is happening? Why does Git require a reference when renaming a branch? and is there a way to rename master before making a first commit? (besides: git: rename local branch failed)


Additionaly:

The following comment suggests that Git is in a 'detached head state,' but I find the explanation unclear. git: rename local branch failed

I thought of detached head as "HEAD is not pointing to a branch (but maybe a commit)". But in my case not only HEAD but also master are not pointing anywhere.


Edit:

using git < v.2.30.0


Solution

  • Why can't I rename master before making a first commit?

    Because you're using a version of Git older than 2.30.0. Since then you should be able to rename the initial branch before making any commits. For example:

    /
    $ git --version
    git version 2.30.0.windows.1
    
    /
    $ git init
    hint: Using 'master' as the name for the initial branch. This default branch name
    hint: is subject to change. To configure the initial branch name to use in all
    hint: of your new repositories, which will suppress this warning, call:
    hint:
    hint:   git config --global init.defaultBranch <name>
    hint:
    hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
    hint: 'development'. The just-created branch can be renamed via this command:
    hint:
    hint:   git branch -m <name>
    Initialized empty Git repository in /
    
    / (master)
    $ git branch -m main
    
    / (main)
    $
    

    This change was introduced in commit cfaff3aac (Dec 11, 2020) and merged in commit 772bdcd4 (Dec 18, 2020). It first appeared in tag v2.30.0-rc1.