How to discard local commits in Git?

GitGit Reset

Git Problem Overview


I'd been working on something, and decided it was completely screwed...after having committed some of it. So I tried the following sequence:

git reset --hard
git rebase origin
git fetch
git pull
git checkout

At which point I got the message

Your branch is ahead of 'origin/master' by 2 commits.

I want to discard my local commits, without having to wipe out my local directory and redownload everything. How can I accomplish that?

Git Solutions


Solution 1 - Git

git reset --hard origin/master

will remove all commits not in origin/master where origin is the repo name and master is the name of the branch.

Solution 2 - Git

As an aside, apart from the answer by mipadi (which should work by the way), you should know that doing:

git branch -D master
git checkout master

also does exactly what you want without having to redownload everything (your quote paraphrased). That is because your local repo contains a copy of the remote repo (and that copy is not the same as your local directory, it is not even the same as your checked out branch).

Wiping out a branch is perfectly safe and reconstructing that branch is very fast and involves no network traffic. Remember, git is primarily a local repo by design. Even remote branches have a copy on the local. There's only a bit of metadata that tells git that a specific local copy is actually a remote branch. In git, all files are on your hard disk all the time.

If you don't have any branches other than master, you should:

git checkout -b 'temp'
git branch -D master
git checkout master
git branch -D temp

Solution 3 - Git

What I do is I try to reset hard to HEAD. This will wipe out all the local commits:

git reset --hard HEAD^

Solution 4 - Git

You need to run

git fetch

To get all changes and then you will not receive message with "your branch is ahead".

Solution 5 - Git

I have seen instances where the remote became out of sync and needed to be updated. If a reset --hard or a branch -D fail to work, try

git pull origin
git reset --hard 

Solution 6 - Git

I had to do a :

git checkout -b master

as git said that it doesn't exists, because it's been wipe with the

git -D master

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
QuestionDaniel C. SobralView Question on Stackoverflow
Solution 1 - GitmipadiView Answer on Stackoverflow
Solution 2 - GitslebetmanView Answer on Stackoverflow
Solution 3 - Gitgiang nguyenView Answer on Stackoverflow
Solution 4 - GitВолодимир ПасікаView Answer on Stackoverflow
Solution 5 - GitJim ClouseView Answer on Stackoverflow
Solution 6 - GitrampView Answer on Stackoverflow