Palak Arora
Palak Arora

Reputation: 1033

Undo git last commit push

I wanted to undo the last changes I made to a file both on my local repo and the repo on Github. (origin)

Could someone please point me to a post/blog of doing it.

Here are the steps I did for committing the changes:

git add -A
git commit -m "changed header"
git push origin master

How can I undo the last changes, both on my local repo and origin.

Upvotes: 2

Views: 1964

Answers (3)

pgilmon
pgilmon

Reputation: 858

Modifying already pushed commits or the history of remote branches is not recommended. If you do so, you would be potentially messing up other people's work, or at least making it more difficult for them to integrate their work back to the remote branch (origin/master in this case).

A way of undoing what you committed without playing with origin/master's history is by creating a new commit that undoes what you previously did, and then pushing that new commit.

First, create a patch that contains the opposite of the changes you made in the last commit:

git diff HEAD HEAD~1 > revert.patch

By issuing that command you are telling Git to create a patch file that describes how to get to HEAD~1 from HEAD (i.e.: to the previous-to-last commit from the last commit).

Then, you apply that patch:

git apply revert.patch

That will apply that patch and modify the files in your working copy. You can delete the patch file now (revert.patch).

Now your working copy is reverted to the state previous to the last commit, but those changes are not into the Git repo yet. You must add and commit them. (Use git gui or git add/git commit, or whatever method you usually use to commit changes).

Once you new commit has been generated, just push it

git push origin master

Now you will have

A'  (master) - (origin/master)
|
B
|
A

Where A' is the new commit you generated, containing the same files as the commit you wanted to revert to (A)

Upvotes: 1

kan
kan

Reputation: 28951

I would prefer to do git revert HEAD, git push origin master unless there is a good reason to use reset.

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 224844

  1. do a hard reset to throw out the bad commit:

    git reset --hard HEAD^
    
  2. force push

    git push -f origin master
    

Note: the reset --hard is going to throw out any changes you made in the most recent commit, unless you still have a branch someplace maintaining a reference to that commit. The previous HEAD will still be in the reflog, though, in case you need it back in the near term. To be very safe, make a backup branch first:

git branch backup master

If everything goes well, you can git branch -D backup later on.

Upvotes: 5

Related Questions