How do I git rebase the first commit?

Issue

I used git init to create a fresh repo, then made three commits. Now I want to rebase to go back and amend my first commit, but if I do git rebase -i HEAD~3 it shows error – fatal: invalid upstream 'HEAD~3'!

If I try the same with HEAD~2 then it kinda works but only lets me rearrange the last two commits.

How do I refer to the ‘commit before there were any commits’ or go back and insert an empty commit?


ERROR with git rebase -i HEAD~3:

fatal: invalid upstream 'HEAD~3'  

Solution

The easy way, with a recent-enough Git (this has been out for a long time now so you should have this):

git rebase -i --root

The other easy way, as twalberg noted in a comment that has since been deleted but is now expanded in https://stackoverflow.com/a/68279810/1256452’s answer, is to use git checkout --orphan to set up to make a new root commit, which you can copy the old commits on top of. (This is what rebase -i --root ends up doing internally anyway.) For some purposes, such as splitting what had been the initial commit, this initial blank commit is helpful.

Side note from the future (2022): It’s often a good idea to make the very first commit contain just a few boilerplate files like a README. The very first commit in any new, empty repository is always a bit special. Note that if you use hosting sites like Bitbucket, GitHub, and GitLab, they will often make such an initial commit for you when you create a repository there, so that you can clone the repository thus created and have a starting point.

Answered By – torek

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published