git: Your branch and 'origin/master' have diverged - how to throw away local commits?

Git

Git Problem Overview


I have the following message in git:

# Your branch and 'origin/master' have diverged,
# and have 3 and 8 different commits each, respectively.
#   (use "git pull" to merge the remote branch into yours)

I would like to throw away the 3 local commits, and pull the 8 remote commits at origin/master.

(Merging is going to be too difficult, I'd rather make the 3 local commits again once master is up to date.)

How can I do this?

Git Solutions


Solution 1 - Git

git fetch origin
git reset --hard origin/master

Solution 2 - Git

To preserve your old commits on a temporary branch in case you need them:

git branch temp

Then switch to the new master

git fetch origin
git reset --hard origin/master

Solution 3 - Git

Try doing this to blow away your local commits:

git reset --hard HEAD~4

Solution 4 - Git

As an alternative to merging, you can rebase the feature branch onto master branch using the following commands:

git checkout feature
git rebase master

Solution 5 - Git

If a hard reset doesn't cut it for you and you don't want to do a pull-merge you can throw away your local unwanted changes by deleting your local branch and re-download the origin one:

git branch -D <local branch>
git checkout -b <branch name> origin/<branch name>

Using main as an example:

git branch -D main
git checkout -b main origin/main

Solution 6 - Git

To erase your latest local commit use the following:

git reset HEAD^

This will get the header back to the state previous to the commit, and will allow you to git pull from master. Make sure you save all your changes elsewhere (locally) before pulling from the remote repository.

To be able to pull without conflicts use git stash, and then git pull.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichardView Question on Stackoverflow
Solution 1 - GitSLaksView Answer on Stackoverflow
Solution 2 - GitjdramerView Answer on Stackoverflow
Solution 3 - GitmanojldsView Answer on Stackoverflow
Solution 4 - GitJosip IvicView Answer on Stackoverflow
Solution 5 - GitGemtasticView Answer on Stackoverflow
Solution 6 - GitBremsstrahlungView Answer on Stackoverflow