I want to remove a git commit that has already been merged in the master branch on bitbucket a while back. In this example I want to remove the commit highlighted in yellow in the image below.
Any help with this please?
I want to remove a git commit that has already been merged in the master branch on bitbucket a while back. In this example I want to remove the commit highlighted in yellow in the image below.
Any help with this please?
There are several ways of solving the problem.
One will safely undo the changes of the commit, and the other will totally remove the commit from the history. Below you can find the details.
This will create a new commit that reverts the changes which were done in that older commit.
To do it you'll just need to run the following command:
git revert <COMMIT_ID>
If there are merge conflicts, resolve it and afterwards push your new commit to remote as usual.
Note: Since this is a new commit, your original commit will stay in the remote, and the new commit will be added to the top. So, the code will be reverted, but the old commit will stay there.
This will totally remove the commit from the log, but might be dangerous if you're working on a team and the other team-members already are doing changes on the same parts.
Let's say you have 5 commits in a branch:
commit1 -> commit2 -> commit3 -> commit4 -> commit5 (HEAD)
you're on the 5th commit (head) and you want to remove the second commit there.
To do so, you'll have to run the following command:
git rebase -i HEAD~4
where -i
is the command for interactive-rebase, and HEAD~4
means rebase the last 4 commits.
After running the command, an editor will be opened with a text like this:
pick d8389ew My Last Commit
pick f7f3f6d Another commit that is okay to keep
pick 310154e A commit that is okay to keep
pick a5f4a0d The commit that I want to remove
There you can see that the commit on the bottom is the one that you want to drop.
You'll need to replace the word pick
with drop
pick d8389ew My Last Commit
pick f7f3f6d Another commit that is okay to keep
pick 310154e A commit that is okay to keep
drop a5f4a0d The commit that I want to remove
Now you can save the file, close the editor and rebase will be done.
There might be some merge conflicts again. If there are, then just resolve them (and do git rebase --continue
if needed to finish it).
After doing the rebase your branch will now look like this (commit2 is removed):
commit1 -> commit3 -> commit4 -> commit5 (HEAD)
So now all you have to do is to force push your branch to the remote.
But WARNING: if you are doing it on a branch on which other guys are working (e.g. master, main), make sure that all they are aware of the changes, otherwise you might break the things.
To push the branch just use the --force
command in the end:
git push origin my-branch-name --force
And afterwards don't forget to let the team-members know to fetch the latest updates on their side.
Notes: