简体   繁体   中英

reverting previous git commit that is not the last one

I have a git project and have about 5 commits ranging from 2-4 files changed. There is one commit I did, affecting two files, which I should not have done with that branch checked out. I would like to revert only the changes made in that specific commit, thus reverting those two files to where they were previously.

These files have no other change history on this branch (again, they shouldn't have been changed on this branch at all). How do I do this?

As a bonus, it would be really cool to "re-assign" this commit to the branch that I should have had checked out at the time, but that's probably over-ambitious. I can always make changes again manually with the correct branch checked out.

One final thing, I use sourceTree, but knowing the CLI method would be good as well.

Not sure I understood you, but what I would have do is reorder the commits and open new branches

First let's say you have those commits:

C5
C4
C3
C2
C1

Now I want to revert commit c3 So I would do

git rebase -i HEAD~3

Now I'll get a new screen that will show me the last three commits, simply change the order of the commits, and place c3 in the last spot.

Now save and run it.

Now for removing the last commit, as for this moment the last commit is c3, simply do

git reset --hard HEAD^

This will reset only one commit back.

After you finished that, you should push your changes to the repository, you can do that with:

git push origin mater -f

We place -f for forcing our changes to the repository.

Just make sure, you are sure in your changes as you are reverting history, and this action is not revertable

Just use git revert . Eg

A----B----C----D
               ^
               |
               master

if you want to revert all changes in commit B a git revert B will result in

A----B----C----D----B'
                    ^
                    |
                   master

If commit B contains a lot of changes and you only want to partitially revert the commit you should read http://www.link-intersystems.com/blog/2015/04/19/how-to-partially-revert-a-commit-in-git/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM