Sourav Kannantha B
Sourav Kannantha B

Reputation: 3299

How to unmerge a previously merged commit in git?

Initially I had this:

> git log --oneline
a807e4a (HEAD -> master) Add test
.
.
.
4a92648 Improve xyz file
f81cae4 Edit xyz file
.
.
.
7cbf3ec Add gitignore

Then I was playing with git, and did some rebases. Now when I log, I get this:

> git log --oneline
547748a (HEAD -> master) Add test
.
.
.
ed9f256 Edit xyz file
.
.
.
7cbf3ec Add gitignore

As you can see, one commit there has been merged with the commit below it, accidentally. It went unnoticed, and I'm noticing it now. When I refloged, I was able to find the missing commit's hash (I guess its correct). But I don't know how to restore it.

If I do git reset --merge 4a92648 then it would go to that commit, but I lose the changes I did after that! Can someone help me to get back that commit without losing the changes I made after that. Note that, these changes are only in my local machine and I haven't pushed them yet.

Upvotes: 1

Views: 82

Answers (1)

Marco Luzzara
Marco Luzzara

Reputation: 6036

Firstly, create a temporary branch while experimenting, in this case you could just do:

git checkout -b temp_branch

Assuming you already are on the branch you want to change.

After that, given that you already have the needed commit hashes, why don't you run a git rebase -i? You are allowed to add new lines (and remove them), and not just changing the current ones. For example, if you need to restore the lost commit, run:

git rebase -i ed9f256^

The editor is going to open and show you pick ed9f256 ... in the first line. Replace that line with:

pick f81cae4 Edit xyz file
pick 4a92648 Improve xyz file

In this way you keep the newly applied changes too. Finally, if you think master should reflect the rebased temp_branch, run:

git branch -f master temp_branch

To update the master branch.

Upvotes: 1

Related Questions