Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git - Undo pushed commits

Tags:

git

I have a project in a remote repository, synchronized with a local repository (development) and the server one (prod). I've been making some commited changes already pushed to remote and pulled from the server. Now, I want to undo those changes. So I could just git checkout to the commit before the changes and commit the new changes, but I'm guessing that there will be problems to push them again to remote. Any suggestion on how should I proceed?

like image 299
Manolo Avatar asked Mar 27 '14 09:03

Manolo


People also ask

Can we revert git push?

If you want to revert the last commit just do git revert <unwanted commit hash> ; then you can push this new commit, which undid your previous commit.

What is the difference between git reset and revert?

For this reason, git revert should be used to undo changes on a public branch, and git reset should be reserved for undoing changes on a private branch. You can also think of git revert as a tool for undoing committed changes, while git reset HEAD is for undoing uncommitted changes.


2 Answers

A solution that keeps no traces of the "undo".

NOTE: don't do this if someone already pulled your change (I would use this only on my personal repo.)

run:

git reset <previous label or sha1> 

this will re-checkout all the updates locally (so git status will list all updated files)

then you "do your work" and re-commit your changes (Note: this step is optional)

git commit -am "blabla" 

At this moment your local tree differs from the remote

git push -f <remote-name> <branch-name> 

will force the remote branch to take this push and remove the previous one (specifying remote-name and branch-name is not mandatory but is recommended to avoid updating all branches with update flag).

!! watch-out some tags may still be pointing removed commit !! how-to-delete-a-remote-tag

like image 38
jo_ Avatar answered Sep 22 '22 12:09

jo_


You can revert individual commits with:

git revert <commit_hash> 

This will create a new commit which reverts the changes of the commit you specified. Note that it only reverts that specific commit, and not commits that come after that. If you want to revert a range of commits, you can do it like this:

git revert <oldest_commit_hash>..<latest_commit_hash> 

It reverts all the commits after <oldest_commit_hash> up to and including <latest_commit_hash>. On some versions of git it also reverts the <oldest_commit_hash>, so double check if that commit gets reverted or not. You can always drop the latest revert commit (which reverts the oldest commit) with g reset --hard HEAD~.

To know the hash of the commit(s) you can use git log.

Look at the git-revert man page for more information about the git revert command. Also, look at this answer for more information about reverting commits.

like image 157
gitaarik Avatar answered Sep 22 '22 12:09

gitaarik