Accidentally commit or do something in Git that you want to undo? Well you’ve come to the right place!

1. Fix a commit

Did not mean to commit that? Type a password and commit[1].? Forgot to stage some files? Don’t fret, the solution is simple, just run:

$ git commit -a --amend -C HEAD
$ git push -f

alternatively, you can stage the files your self (e.g. git add .) and just do:

$ git commit --amend -C HEAD
$ git push -f

2. Entirely Undo a Commit

2a. keep changes

If you want to remove the commit but keep the changes you have simply do:

$ git reset --soft HEAD~

This will remove the commit from git (git will never know what happened), but will leave your files unchanged. It’ll be as if you never made that commit.

2b. discard changes

If you want to remove the commit and loose your changes. i.e. revert your files too, do:

$ git reset --hard HEAD~

Want to remove more commits. HEAD represents your most recent commit. HEAD~1 (shorter version is HEAD~) matches your second most recent commit. HEAD~2 is your third most recent. Simply replace HEAD~ with the correct value.

Additionally, you can use git log to find the commit you want to revert to, locate the commit’s SHA and paste that in instead of HEAD~.

3. Reverting to last commit

If you’ve read the previous section you might figure this out but let’s say you’re coding and you’ve made a mistake and just want to revert your entire code back to your last commit. Just do:

$ git reset --hard HEAD

Reverting just some files/folders

Only want to revert some files or folders? That’s easy too:

$ git checkout -- src/folder/ also/revert/this/file.txt

Want to revert the files to an even earlier commit? Use:

$ git checkout <commit> -- <files>

Where <files> are your files and <commit> is a string representing a commit as described as above (e.g. HEAD~ for second most recent commit)


Hopefully this post helped or you learned something. Git can be confusing at times but hopefully I explained everything clearly. If you have any questions don’t hesitate to leave a comment!


  1. If this is the case. Immediately assume the password is compromised and change it everywhere. ↩︎