Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git undo pushed merge and delete its history

Tags:

git

git-merge

I made an accidental merge to master and pushed it, now master has all the commits from dev. I want to revert the commits from master and delete its history without changing dev. How can I do that?

like image 584
Shubham Chaudhary Avatar asked Jun 04 '26 15:06

Shubham Chaudhary


2 Answers

The last commit can be removed with: git reset --hard HEAD^.

Sometimes there might be situations, when you need to remove a commit from the "middle" of branch. Here comes to the rescue interactive rebase: git rebase -i <commit>^. You just need to drop an unwanted commit (it should appear at the top of the list).

If the changes you undone were available in remote, they also should be removed from there with force push: git push --force.

However, rewriting the history of a branch, that has been shared with someone, is not a good way of undoing changes. Instead, consider to use git revert <commit>. This is the more robust and correct way in this situation.

I'd recommend to read Git Branching - Rebasing. Chapter "The Perils of Rebase" is explaining why rewriting the public history is not a good idea.

like image 66
Vitali Avatar answered Jun 06 '26 06:06

Vitali


$ git revert -m 1 <merge-commit-hash>
  1. git revert will make sure that a new commit is created to revert the effects of that unwanted merge. This is in contrast to git reset, where we effectively "remove" a commit from the history. That's also the reason why git revert is a better solution in cases where you've already pushed to a remote.

  2. The -m 1 option tells Git that we want to keep the parent side of the merge (which is the branch we had merged into).

  3. Finally, also make sure to provide the correct commit hash: for the git reset example above, we had to provide the commit before the merge; when using git revert, however, we have to specify the actual merge commit's hash.

https://www.git-tower.com/learn/git/faq/undo-git-merge/

like image 42
Farhad Avatar answered Jun 06 '26 06:06

Farhad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!