Accidentally commit or do something in Git that you want to undo? Well you’ve come to the right place!
Did not mean to commit that? Type a password and commit1.? 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
$ git commit --amend -C HEAD $ git push -f
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.
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
HEAD~2 is your third most recent. Simply replace
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
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
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>
<files> are your files and
<commit> is a string representing a
commit as described as above (e.g.
HEAD~ for second most recent
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!
- If this is the case. Immediately assume the password is compromised and change it everywhere.↩