Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to discard local commits in Git?

Tags:

git

git-reset

People also ask

How do I discard a local commit?

If your excess commits are only visible to you, you can just do git reset --hard origin/<branch_name> to move back to where the origin is. This will reset the state of the repository to the previous commit, and it will discard all local changes.

How do I discard changes in git?

There are two Git commands a developer must use in order to discard all local changes in Git, remove all uncommited changes and revert their Git working tree back to the state it was in when the last commit took place. The commands to discard all local changes in Git are: git reset –hard. git clean -fxd.


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.


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

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

git reset --hard HEAD^

You need to run

git fetch

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


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