When using Git, sometimes we may find we are in situations that some changes (or files) were commited by mistake and we want to remove them permanently from the repository. Listed below are the steps to do that.
For example, we have following configuration. We committed three changes and we want to remove the second one (with hash bbbbbb).
HASH COMMENTS
aaaaaa Initial commit
bbbbbb The commit we want to remove
cccccc Some other changes
To remove the bbbbbb, we can use git rebase
command. One way to use it is as follows.
git rebase --onto bbbbbb^ bbbbbb
Another (safer, I think) way is to use git rebase -i aaaaaa
. The command will open up a VIM editor, in which each commit after aaaaaa lies in a single line.
pick bbbbbb The commit we want to remove
pick cccccc Some other changes
To remove commit bbbbbb, we can simply delete the line pick bbbbbb
, save and exit VI (:wq
).
Now, if you run git log
you would not see bbbbbb any more. But the disk space occupied by the commit is not release yet. That is because Git has reflog feature, that will keep unreachable objects for a period of time (3 months initially?). The following command can be used to release the disk space at once. Think again before you run it!
git reflog expire --all --expire-unreachable=now
git fsck --unreachable
git gc --aggressive --prune=now
The are many other usages of git rebase -i
. For example, change comments, combine two commits to one, etc. Please refer to its document for more details.
No comments:
Post a Comment