user3670011
user3670011

Reputation: 194

How to revert git repo while preserving the commit history?

Here's what I have:

dbd7868 (HEAD -> master) commit 3
19ea7e8 commit 2
5b4baae commit 1

I want all files to be in the exact same state as they were in commit 2. Here's what I tried:

git checkout 19ea7e8
git commit -m "reverted to commit 2"

But this was the result:

HEAD detached at 19ea7e8
nothing to commit, working tree clean

Desired result:

xxxxxxx (HEAD -> master) reverted to commit 2
dbd7868 commit 3
19ea7e8 commit 2
5b4baae commit 1

I tried looking around but I found answers where a command would've left commit 3 out of the history and then I found answer where it was not clear if the history was preserved or not.


Edit: I had to set the test project again after trying one of the suggested solutions. Here's what I have now:

9c4180f (HEAD -> master) jkl
38029d0 ghi
830efcd def
ae96f00 abc

Here's what I want:

xxxxxxx (HEAD -> master) def again
9c4180f jkl
38029d0 ghi
830efcd def
ae96f00 abc

Commit def again should be exactly the same as def. To clarify, I want to be able to go to any commit.

Upvotes: 3

Views: 1181

Answers (2)

user3670011
user3670011

Reputation: 194

I found the solution thanks to John Ilacqua.

Here are the exact commands I entered:

git checkout 830efcd .
git commit -am "revert def"

And here's the output:

684b0bb (HEAD -> master) revert def
9c4180f jkl
38029d0 ghi
830efcd def
ae96f00 abc

Upvotes: 1

Pankaj Singhal
Pankaj Singhal

Reputation: 16053

You can use the command git revert <hash1> <hash2> ..

Try the following command:

git revert dbd7868

It will create a new commit which will be a revert of commit 3.

If you want to revert any other commit, just run the revert command with the commits hash. Eg:

git revert 5b4baae #to revert commit 1
git revert 19ea7e8 #to revert commit 2

In all cases, the revert commit will come on top of commit 3.

Upvotes: 7

Related Questions