Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git - How to revert a rebase that has been pushed to the remote branch (not origin)

Tags:

git

git-rebase

I was working on my local branch doing some changes and when I finished I pushed everything to the remote brach. Before merging the branch with develop I thought I should do a rebase cos the other guys had merged a lot of their code there. When I did the rebase and resolved some conflicts I pushed to the remote branch. Unfortunately the way I resolved the conflicts was wrong so now I need to go back before the rebase happened and also update the remote branch to the new state.

What I tried

  1. Reset the head

    git reset --hard HEAD@{x} //where x is the head just before the rebase

This works and reverts the changes on my local branch but then I don't know what to make the remote branch update to that since it doesn't create a new commit that can be pushed to the remote.

like image 418
user1844566 Avatar asked Nov 22 '12 13:11

user1844566


People also ask

Can you revert git rebase?

Simply take the commits that you want to get rid of and mark them with "d" instead of "pick". Now the commits are deleted effectively undoing the rebase (if you remove only the commits you just got when rebasing).

Which command is useful to undo a git rebase?

To undo the rebase , we can use the reflog command of Git. Using git reflog , we can determine the branch's head commit immediately before the rebase starts.


2 Answers

Dont panic! just follow these steps in terminal

git reflog 

or

git log -g

This will show previous commits in terminal like

enter image description here

here commits are named as HEAD@{0}, HEAD@{1} etc. if you want to revert lastest changes than in attached pic HEAD@{5}, but it varies according to your commits

git revert HEAD@{5}

Its done. Now you see all files as before commits

like image 109
saud00 Avatar answered Oct 15 '22 04:10

saud00


You should not rewrite the history of remote repositories because if

  1. You push something broken
  2. Somebody pulls
  3. You force-push a different history

not only would you have the issue of having to fix the mess but everybody else who pulled the changes. So unless you can be sure that nobody pulled it, don't do a force-push.

Instead you should revert the commit using either

>> git revert HEAD@{y}   # where HEAD@{y} is the faulty commit

if only one commit was messy, in case of a merge.

In case of a rebase that transplatend several commits onto the master branch you need to do

>> git revert --no-commit HEAD
>> git revert --no-commit HEAD~1
>> git revert --no-commit HEAD~2
   ...
>> git revert --no-commit HEAD@{x}
>> git commit -m "Sorry folks for the big mess I made"

Where all the HEAD~y are the commits in between HEAD@{x} and HEAD.

This will effectively undo all affected commits in a single big commit.

like image 28
Nils Werner Avatar answered Oct 15 '22 02:10

Nils Werner