Fixing the "fatal: Not a valid object name: master" Git Error
I'll describe a common Git error and how to resolve it.
The Error
fatal: Not a valid object name: 'master'
This error happens when trying to create a branch when there is no master branch.
The Problem
Let's take a look at an example:
$ git init
Initialized empty Git repository in /users/amanpalod/gitblog/.git/
$ git branch feature-1
fatal: Not a valid object name: 'master'.
A master branch is created after our first commit. Let's commit a file and check the branch list:
$ touch test.txt
$ git add test.txt
$ git commit -m "First commit"
[master (root-commit) dffc881] First commit
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 test.txt
$ git branch
* master
Since master has been created, we can now create a branch:
$ git branch feature-1
$ git checkout feature-1
Switched to branch 'feature-1'
Why This Happens
When you initialize a new Git repository with git init, Git doesn't create any branches until you make your first commit. The master branch (or main branch in newer repositories) only exists after there's at least one commit in the repository.
The Solution
- Make your first commit before trying to create additional branches
- Use
git checkout -b feature-1instead of separategit branchandgit checkoutcommands - Check if you are in a Git repository with
git status
Alternative Approach
You can also use the newer Git syntax to create and switch to a branch in one command:
$ git checkout -b feature-1
Switched to a new branch 'feature-1'
This approach works even if the master branch doesn't exist yet, as it will create the branch based on your current HEAD.