Home > Blockchain >  How can I roll back several Git commits into new branch?
How can I roll back several Git commits into new branch?

Time:09-14

If I have a commit tagged say v0.3.1 and a bunch of commits since then (all on main), how can I roll back all commits since v0.3.1 and put them in a new branch feature, then delete the original commits from main?

CodePudding user response:

Switch to your main branch, create a new branch for the feature and do git reset --hard commit_you_want_to_reset_to on the main branch.

Now your main branch should be at the commit you chose, while you have now a branch that still has all the code from the feature.

CodePudding user response:

There are many ways to do this, but for fun, here is perhaps the most efficient way possible, using a two-liner which leaves you on branch feature where you wished you were in the first place:

# switch to a new branch feature which is identical to the current main
git switch -c feature main

# re-point main to tag v0.3.1
git branch -f main v0.3.1

Note if you already pushed main, you'll need to force push main to update it, but, in that case you also will want to decide if force pushing main is a good idea for this repo, since it's generally frowned upon.

  •  Tags:  
  • git
  • Related