dabadaba
dabadaba

Reputation: 9542

How do undo and stash a previous commit which is not the last?

I wonder if that's possible at all. I committed some changes, commitA and then some more and more... commitB, commitC. Now I realized I don't want commitA in the code for the moment, they need to be reviewed first.

So I need to undo that commit and stash it for review and commiting them again. Is there a straightforward way to do this? Or should I just revert those changes manually, commit the revert, then introduce the changes again and stash them?

Upvotes: 0

Views: 130

Answers (2)

eftshift0
eftshift0

Reputation: 30317

Hmm..... i had already answered something like this... suppose some-branch is pointing to commitC

git checkout commitA
git reset --soft HEAD~
git stash save 'stashing commit A'
git rebase --onto HEAD commitA some-branch # get rid of commit A

Upvotes: 1

Calum Halpin
Calum Halpin

Reputation: 2105

If you've already shared the commit then yes, you're better off reverting it and recommitting later after review. If you haven't then you can just do an interactive rebase. Starting from a clean working directory:

git rebase -i <commitA>^

A text editor will open a file something like this:

pick <commitA> some commit message...
pick <commitB> blah blah...
pick <commitC> blah blah...

Change the "pick" by to "edit", save, and quit the editor. will be automatically checked out.

git reset HEAD^
git stash -u
git rebase --continue

The remaining commits will be replayed without .

Bear in mind if later commits rely on then you'll get merge conflicts.


As pointed out by sbat in the comments; if you do decide to revert you don't need to manually undo your changes. You can use the git revert command.

Upvotes: 2

Related Questions