How to reset the first commit in Git?

Atomic Dec 22, 2020

When we would like to make a change in the first commit on master, we cannot use interactive rebasing and resetting. Both of them have security mechanisms to prevent this action. Instead, we either have to change our master (using —orphan) or delete the branch while we're on it.

Don't use rm -rf .git. This command deletes everything related to Git in the repository. We will lose all the branches and the commits.

Let's change the master branch.

First, we need to rename the master branch. (We assume a branch named old_master doesn't exist yet)

git branch -m master old_master

-m or --move is used to rename/move the branch and its reflog. This moves everything (all the commits and history) from the master branch to the old_master branch. Now our branch looks like this: old_master:master.

Next, we need to create an orphan branch from the current head.

git checkout --orphan master

--orphan creates a new branch without a root so that the newly created branch doesn't have a history and a parent. The new branch is totally disconnected from all other branches and commits. But it still has all the files from the old_master since we created a new branch while we were in the old_master branch.

The last thing is deleting the old_master since we don't need it anymore. (We can keep it to preserve history if we want to.)

git branch -D old_master

Now we have the latest changes, and we are in a brand new master branch. But there is another way to do this with a single command. We need to make sure we're on the master branch.

git update-ref -d HEAD

This command deletes the branch we are in. If we are in master, this command will delete the master branch, and all the commits.

Candost Dagdeviren

Sr. Software Engineer. Writes about software engineering, leadership, tech, cultural differences, and their effect on people.

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.