Git: Delete commits from a branch

Using Revert feature in Git will keeps the older commit in the branch. It just revert the changes what we have done in a commit. The Revert also will shown as a separate commit in the branch.
But if you want to remove a commit from a branch permanently, you need to use git reset command as below
git reset --hard HEAD~1
Here HEAD~1 means, the commit before the head.
If you want to reset up to a particular commit, use
git reset --hard 
If you already pushed the commits to the repo, you need to use as 
git push origin HEAD --force
This will reset your branch up to the given commit. 
Note: Be careful before doing the above as these will remove the changes in the working directory. Better to keep a backup for the working folder.

Example

The following process will show how it works
1) I have a repo named "test" in my bit bucket. 




It has two branches "master" and "my-branch". "master" branch contains 2 commits and "my-branch" contains 8 commits (along with two master branch commits). 
2) Now I want to reset my-branch to the commit "666f88d" ("fourth.html added") commit. So I just reset my-branch with the command
git reset --hard 666f88d

3) It will reset the changes in your local folder only. Push the changes to repo using
git push origin HEAD --force

4) Now those commits will also be removed from the bitbucket branch


Note: Actually, the commits will not remove from the repo. They just removed from the tree. If you have the direct link to the deleted commit and if you open that link, you can sees the changes you made on that commit

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment