Git: Delete Last Commit

Many times like you, even professional programmers do mistakes. A lot of times it happens that you commit something junk in hurry and then you start looking out for reverting it back. Like you even I have done such mistakes many times and finally I thought to write down a few useful git commands which will help me to revert back to stable copy of project.

Using ‘git reset’

So, if you have committed something junk, not useful but you have not pushed it to remote repository then you can go with

git reset --soft HEAD~1

git reset‘ command will reset your current commit. The ‘HEAD~1‘ mentioned here is nothing but shorthand for your last commit and the ‘–soft’ option specified in the command will keep all the changes in working copy.

Consider we have following three commits,

Git Commits Screenshot

and now we want to delete our last commit i.e. commit 3. So if we use the git reset –soft HEAD~1 command then result will be,

Git reset commit result

Note, since we have done soft reset, all changes which we have done in commit 3 are now in working copy.

If you want to hard reset your repository then you can go for ‘–hard’ instead of ‘–soft‘. This option will delete your last commit and all changes made including working copy.

If you want to move back to specific commit then you can use SHA-1 id of the commit at place of the HEAD~1. Example if you want to move commit whose SHA-1 if is 3518a64 then you can use

git reset --soft 3518a64

Note here we are using –soft, so all the changes made will be preserved.

Using ‘git revert’

The ‘git reset’ command works only when you have committed something and it is not pushed to remote repository. But if you have committed something and pushed it to remote repository then rather than ‘git reset‘ you have to go for ‘git revert‘. simply use

git revert HEAD

and then push or sync your repository. You will see that a new commit is created which do not include anything introduced by accidental change.

Considering same example as above, we are having three commits as follows

Git Commits Screenshot

and consider we have pushed everything to remote repository. Now if we use ‘git revert HEAD‘ then the result will be…

Git revert commit result

Now if you go through your working copy, you will find that all the changes made in last junk commit are discarded.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.