Steverino
Steverino

Reputation: 2266

Undo Multiple Git Commits in a Row but Keep All Changes

I see many questions/articles describing how to undo a commit but keep the changes. What if I have made multiple enthusiastic (read: ill-advised) commits, to the wrong branch?

Here is the situation in a picture:

A -> B -> C

All of these changes are on master branch.

A is the last time master branch was correctly in sync with remote.

B was a set of changes that I made. The changes are good and I want to keep them, but committing them to master branch was a mistake.

C was another set of changes I made. These were also committed to master. Stupid! I want to keep these changes, but also not on master.

How can I get master branch back to state A while keeping all the changes from both B and C, so that I can commit them all to a new feature-fix branch?

I want to see this:

A -> (all changes from B and C as unstaged changes)

Note: I have not pushed anything to remote yet so this is all safely in my local repo.

Upvotes: 1

Views: 130

Answers (1)

Jonathan.Brink
Jonathan.Brink

Reputation: 25443

You need to move your HEAD pointer back to A, which calls for the reset command:

git reset A

This form of reset (--mixed, the default) will take the changes that you "re-setted" over and leave them in your working directory while your master branch will point back to A.

So, after you run this command, a git diff should show the contents of B and C.

After this, you could move those un-staged changes over to a separate branch:

git checkout -b feature-fix
git add .
git commit -m "changes"

Upvotes: 4

Related Questions