-1

I'm new on Git and I've delete my last two commits which already pushed to github by this command:

$ git reset --hard HEAD~2

and now when i want to push new commits to my own branch ( jsonadd ) to github I'm facing following :

$git push -u origin jsonadd
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.

appreciated if you could let me know how can I fix it. thanks guys

Siavoosh
  • 181
  • 1
  • 1
  • 5
  • So you want to remove those two commits that you removed from your local repo, from github repo as well? And then push some new commits? – Brenda J. Butler Jan 05 '20 at 09:51
  • if the issue will be solved by this, I need to say yes. how can I delete those deleted local commits from github as well. – Siavoosh Jan 05 '20 at 09:54
  • Well, I can give a different solution ... what solution do you want? If you want to keep the commits in github, I can solve it that way too. Just say what you want. – Brenda J. Butler Jan 05 '20 at 10:00
  • Does this answer your question? [Cannot push to GitHub - keeps saying need merge](https://stackoverflow.com/questions/10298291/cannot-push-to-github-keeps-saying-need-merge) – phd Jan 05 '20 at 12:33
  • https://stackoverflow.com/search?q=%5Bgit%5D+hint%3A+Updates+were+rejected+because+the+tip+of+your+current+branch+is+behind – phd Jan 05 '20 at 12:33

1 Answers1

0

The correct next step in your workflow after the hard reset should have been to force push the branch to GitHub:

git push --force origin jsonadd

The force push is required because you rewrote the history of this branch by resetting it. Without force pushing, any subsequent commits you made locally cannot be applied by GitHub, which would be unable to relate the commits to the original history which still exists on the remote.

I mentioned the "correct" next step you should have taken, but, most of the time, rewriting the history of a Git branch which has already been published is not desirable. It is not desirable because doing so can cause problems for anyone else sharing the branch. Such users would encounter the same errors you are facing now, which prompted you to post a question here. A much better strategy would have been to revert the two most recent commits:

git revert HEAD~2..

This option would apply two new commits which would functionally undo whatever the two most recent commits were doing. If you just want a single merge commit, then use:

git revert --no-commit HEAD~2..

Note that the git revert approach is safe with regard to your branch possibly being shared by other users. Should they pull your revert work, nothing unexpected would happen apart from the removal of certain features intended by the revert.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360