I want to undo my push to the main branch which is merged as well.
Note: I remember that pushing to the main branch isn't a good practice, but there were some commits showing in my main branch of the local repository. So, just to check these commits, I pushed the code, assuming that it'd not be merged automatically. But now, on viewing the remote repo, it seems to be merged in the main branch. Is there a way to undo this merge?
It did not get merged automatically, in fact, a merge technically wasn't performed at all. You committed directly to the main branch and pushed those changes up to your remote. This is the intended behavior!
What you probably wanted to do was create a new branch locally using a command like
git switch, then commit to and push your changes to that branch instead.Regardless, there are two ways you can "undo" the commits you've introduced to
main.In either case, you should use
git logto find the commit reference you want to go back to. For my examples, I will be usingHEAD~3, which means 3 commits behind the current state of the repository. This assumes I've made 3 commits I'd like to undo.Revert
If you don't mind a cluttered Git history, you can use
git revertwhich inverts the specified commits. For example, if you added 5 lines, this will introduce a new commit that removes those 5 lines.This is what you should be doing in almost all circumstances when working with shared or protected branches. The only exceptions are particularly sensitive scenarios, like if you accidentally committed credentials.
Example:
This will introduce 1 new commit, which will reverse the changes made in the last 3 commits to
main.Reset
This will remove the commits, and thus alter the Git history. This is generally not a good idea for shared branches like
main.If this is the approach you want to take, you can do a hard reset with the
git resetcommand.This will reset your history back to the specified commit reference, which you can then force-push to your remote and modify the history.
Depending on your remote settings, you may have to explicitly enable force-pushing to protected branches.
Example:
This would reset your local repository to 3 commits ago, then force-push up to your remote, which will remove the 3 commits from there too.
If you want to preserve the changes from the 3 commits, then it might be better to do a soft reset instead, and stash the changes before force-pushing.
Example:
This will achieve the same thing, but the changes you undid will remain unstaged in your working directory.