7

I have pushed on the wrong branch, I want to push on new branch but I have pushed on the master branch. Is there any way to Reverse the last committed push and get the last code and pushed again to the new branch?

Habib
  • 846
  • 2
  • 9
  • 24
  • 1
    Possible duplicate of [How can I remove a commit on GitHub?](https://stackoverflow.com/questions/448919/how-can-i-remove-a-commit-on-github) – Remy J Jun 07 '17 at 05:52
  • I don't want to delete my last commit, I want to edit my last commit. So how can I do it? I just want my last commit work in my local changes. Does it possible? – Habib Jun 07 '17 at 05:54
  • You mean edit the last commit message? – Remy J Jun 07 '17 at 05:56
  • No, I mean to say that I want to push my last commit from master to my any local branch. – Habib Jun 07 '17 at 06:04

2 Answers2

12

Undo the last commit by soft reset from local master branch and keep the changes locally (in working tree).

$ git checkout master
$ git reset --soft HEAD~1

$ git log               # make sure the last commit is reverted successfully as you expect.

Checkout to a new branch (say, feature). Add, Commit, Push to remote branch (feature here).

$ git checkout -b feature   # checkout new branch with the local changes
$ git status                # see the changed files
$ git add .
$ git commit -m 'message'
$ git push origin HEAD

Back to local master and do force push to update the remote master (delete remote master's last commit)

$ git checkout master
$ git push -f origin HEAD

N.B: Force push needed since changing the history of the remote master.


Alternate: If you don't have force push permission or someone else Pulled the origin/master and got your last commit already. Then better you revert the last commit instead reset (history change).

$ git checkout master
$ git log                        # copy the last-commi-hash
$ git revert <last-commit-hash>
$ git push origin HEAD           # note, no force push is needed

Create a new branch and cherry-pick the last commit and push to remote.

$ git checkout -b feature
$ git cherry-pick <last-commit-hash>
$ git push origin HEAD     
Sajib Khan
  • 22,878
  • 9
  • 63
  • 73
  • I am in my master branch, where I have pushed my commit. I run this command `git reset --soft HEAD~1` but I can't see any files in local changes. Where the files gone? They are also not in the git log. – Habib Jun 07 '17 at 06:08
  • 1
    Did you run `git reset --hard "commit id"` before as @Moses Nandwa told? – Sajib Khan Jun 07 '17 at 06:10
  • 1
    `git reflog` will show you the whole history of commands you executed. Just copy your last commit hash and checkout to that commit by `git checkout `. Now follow the answer. – Sajib Khan Jun 07 '17 at 06:23
  • Its very helpful and it done what I want, Thank you. – Habib Jun 07 '17 at 06:25
0
git log 

This will give you a log of all the commits and then git reset --hard "commit id" This will reset to the given head

Moses Nandwa
  • 179
  • 2
  • 3