Question

Say I make a bunch of changes to my files locally, then add these changes to the staging index and then commit them. Then I realise that actually, I've made some mistakes, and I want to quickly undo that whole commit and get back to where I was right before I committed (ie with my changes out of the repo and back in the index).

I tried to do a git revert SHA and this did indeed undo my most recent commit, but it also completely overwrote all my files and put them back into their original state.

How do I revert a commit without it overwriting my changes?

Was it helpful?

Solution

You're looking for git reset --soft <last commit you want to keep>.

Note however that unlike revert, this will undo all of the commits after the one you specify (e.g. if you have A-B-C-D (HEAD) and you git reset --soft B, both C and D will be undone, with both of their changes left in the index).


Of course, another option is to not undo your last commit, but instead just modify it to get rid of the mistakes. You can do this via git commit --amend, which acts just like git commit except that instead of creating a new commit, it modifies (amends) the latest existing commit.

git commit -m "this commit has mistake(s)"
...edit the file(s) with mistake(s)...
git add <file>
git commit --amend -m "same commit, no mistake(s)"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top