Git is a popular distributed version control system used by developers in many organizations. Sometimes you may need to delete one or more commits in case you accidentally made them, or for some other reason. In this article, we will learn how to delete commits in git.
How to Delete Commits in Git
You can easily delete commits in git using git reset command. But there are a few things to keep in mind, while working with it, as you can see below.
Before you run the following commands, it is advisable to use git stash to save all the changes in your present branch.
Here is the command to delete the previous commit in your existing branch. It will delete the last commit of your present working branch.
$ git reset --hard HEAD~1
The number ~1 indicates that you want to delete the last 1 commit. If you want to delete last 5 commits, replace 1 with 5 above.
$ git reset --hard HEAD~5
The above command will take your HEAD back by 5 commits.
If you want to go back to a specific commit, find its commit id using git log command, and then use git reset as follows.
$ git reset --hard <sha1-commit-id>
The above commands will only delete commits locally. What if you want to remove them from the remote origin/branch also where you had pushed these commits earlier. In such cases, use the following command after you have deleted commits locally.
$ git push origin HEAD --force
That’s it. In this short article, we have learnt how to delete commits from git. You can delete commits from any branch including master branch. You need to first switch to that branch, before you run the above commands.
Also read:
How to Set User Agent with cURL
How to Unzip File in Linux
How to Uninstall Package in CentOS
Limit Bandwidth & Connection in Apache
How to Remove Local Untracked Files in Git
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.