If you have accidently committed the wrong files in the Git but have not pushed the committed code yet and you want to know how to undo the most recent local commits in Git, don’t worry you can revert back this very easily. This article will help you to do this very easily.
Sometimes we do such type of mistakes in hurry. You can undo the not only last commit but also any of the previous commits. Once you got reverted the unwanted commit then you can make the necessary changes and commit again and can push it to the remote repository.
Here are the different way to undo the last Git commits:
$ git commit -m "Something committed by mistake" - # Your last commit done by mistake $ git reset HEAD~ - # HEAD~ means your last commit, HEAD~1 is similar to HEAD~
Now you can do your required changes. After finishing your changes you can add, commit and push as steps give below.
$ git add . $ git commit -m "Your new comments" $ git push origin your_branch_name
If your are not sure about the numbers of commit then use below command to check the logs of all the commits you have done.
$ git reflog
Based on the above logs of your commits you can choose the commits id to revert.
Below command will revert the last commit but also it will remove the files/changes you have done in the last commit.
git revert HEAD
Soft Reset Git Commit
Revert last Git commit and keep the changes at your local system as it is.
If you want to only revert the last commit from the Git history but don’t want to remove the changes then you can use below syntax.
$ git reset --soft HEAD~1
Hard Reset Git Commit
If you want to undo your last commit and also want to delete those changes then you can use below syntax.
$ git reset --hard HEAD~1
Thanks for reading this article. If you have any query please let me know through the comment box. If you like this article please share. Thanks.