GIT Undoing Rebase or Reset Rebase


In this tutorial, we will see how to undo rebase:

  • First, use the git reflog command to find the commit ID of the commit you were on before the rebase. This will show you a list of all the recent HEAD positions in your repository.
  $ git reflog
  • Once you have found the commit ID of the commit you were on before the rebase, use the git reset command to reset your branch to that commit ID.
    $ git reset --hard <commit ID> 

For example, if your commit ID is abc123, you would run:

$ git reset --hard abc123
  • Finally, force push the reset branch to your remote repository.

$ git push -f origin <branch name>

For example, if your branch name is master, you would run:$ git push -f origin master

Note: Use this command with caution, as it can overwrite other changes that may have been pushed to the remote repository. It’s always a good idea to communicate with other collaborators before using git push -f.

That’s it! Your repository should now be back to its pre-rebase state.

$ git reflog //get commit hashid
$ git reset --hard 4985258
HEAD is now at 4985258 adding file3

jayaramp@jayaram MINGW64 /d/GITDemo/gitdemo (main)
$ git status
On branch main
Your branch and 'origin/main' have diverged,
and have 3 and 1 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

nothing to commit, working tree clean

jayaramp@jayaram MINGW64 /d/GITDemo/gitdemo (main)
$ git push -f


jayaramp@jayaram MINGW64 /d/GITDemo/gitdemo (main)
$ git log --oneline
4985258 (HEAD -> main, origin/main, origin/HEAD) adding file3
da0a945 adding file2
bc30c80 adding file1 and java
225cf45 (origin/feature/new, feature/new, dev_v1) Initial commit

Demo:

As shown below, successfully rebased and squashed commits. Lets undo this operation.

GIT reflog: git reflog and as shown in below we will revert to 4985258 commit.

GIT Reset