Starting a new git branch in the past

Imagine you started working on a new feature and realized you didn't start a new branch, so all your recent commits accidentally went to main. I do this all the time.

If you didn't push your working branch to the upstream, there is an easy fix.

First, create a new feature branch from the HEAD:

git checkout -b new-branch-name

Then move your integration branch to the past (assuming the branch name is main, and you want to start new-branch-name 3 commits ago from the HEAD):

git branch -f main HEAD~3

HEAD~3 means "third last commit from the HEAD" (if HEAD is your current checked-out commit, HEAD~1 is the previous one, etc.).

The alternative syntax for this example is HEAD~~~. It can be easier to type unless you must go too deep into the past.

It becomes more tricky if you merge something in the recent commit history. Git provides a ^ (caret) shortcut for ancestry reference in the case of multiple parent revisions. But I'd prefer ordinary commit ids. It is not as easy to mess up compared to caret syntax.

References:


git

Somewhat related: