How can I go back to previous state before rebasing?
Undoing the rebase operation
You can use the git reflog
command to see the history of what has been done in your git. It records when the updates to the tip of branches and other references were updated in the local repository. Default is 90 days before gc (garbage collection).
You will see a list of every thing you have done in Git, across all branches. Each line will start with an index like HEAD@{5}
, and show what that HEAD pointed to at that point in time. Find the place where you want to go back to and use the index to reset your HEAD to that point.
git reset --hard HEAD@{5}
Be careful with git reset --hard
command. It will delete any uncommitted changes.
Or can I solve this from the point I am on now?
Interactively rebasing and dropping the commits
First, find the commit hash you want to go back to. That should be the commit just before the first commit you want to remove. You can find this by using git log
command.
Once you have got the commit hash, you can start an interactive rebase with the parent of that commit.
git rebase -i <commit-hash>^
In the text editor that comes up, you will see a list of commits that will be rebased (played back). To remove a commit, delete the line or replace pick
with drop
or d
. Once you are done, save and exit the editor.
Git will then replay the remaining commits. If there are conflicts, it will pause and allow you to resolve those conflicts; after which, you can continue the rebase with git rebase --continue
.
If you decide at any point that you want to stop the entire process and go back to where you were, you can use git rebase --abort
.
Once you are done, you can push your changes to the remote repository.
If the branch has been pushed before, you will need to use git push --force origin branch-name
to force the push.
Warning: Force pushing can be dangerous if others are working on the same branch, as it can overwrite their changes. It is a good idea to communicate with your team before doing a force push.
The git push --force-if-includes
that I mention here can help secure that step.