乐闻世界logo
搜索文章和话题

How to move the most recent commits to new branch with git?

2个答案

1
2

For those curious about why it works.

You want to reset to commit C and move commits D and E to a new branch.

Initially, it looks like this:

shell
A-B-C-D-E (HEAD) master

After git branch newBranch:

shell
newBranch A-B-C-D-E (HEAD) master

After git reset --hard HEAD~2:

shell
newBranch A-B-C-D-E (HEAD) master

Since branches are simply pointers, master points to the latest commit. When you create newBranch, you simply create a new pointer pointing to the latest commit. Then using git reset, you move the master pointer back two commits. But since you didn't move newBranch, it still points to the commit it was initially created on.

2024年6月29日 12:07 回复

There's another way to do this with just two commands. You can also keep your current work tree intact.

shell
git checkout -b newbranch # switch to a new branch git branch -f master HEAD~3 # reset master to point to an older commit

Old version - Before I knew about git branch -f

shell
git checkout -b newbranch # switch to a new branch git push . +HEAD~3:master # make master point to an older commit

Being able to push with . is a handy trick.

2024年6月29日 12:07 回复

你的答案