Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw away local commits in Git

Tags:

git

Due to some bad cherry-picking, my local Git repository is currently five commits ahead of the origin, and not in a good state. I want to get rid of all these commits and start over again.

Obviously, deleting my working directory and re-cloning would do it, but downloading everything from GitHub again seems like overkill, and not a good use of my time.

Maybe git revert is what I need, but I don't want to end up 10 commits ahead of the origin (or even six), even if it does get the code itself back to the right state. I just want to pretend the last half-hour never happened.

Is there a simple command that will do this? It seems like an obvious use case, but I'm not finding any examples of it.


Note that this question is specifically about commits, not about:

  • untracked files
  • unstaged changes
  • staged, but uncommitted changes
like image 884
David Moles Avatar asked Feb 23 '11 21:02

David Moles


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 remove local and remote commit?

To remove a commit you already pushed to your origin or to another remote repository you have to first delete it locally like in the previous step and then push your changes to the remote. Notice the + sign before the name of the branch you are pushing, this tells git to force the push.

How do I remove Unpushed commits?

Use the git reset Command to Remove Unpushed Commits in Git. Whenever we want to commit changes to the project directory, we can commit the changes using the git add and git commit commands. When using the git commit command, a commit is created in the local Git repository.

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.


1 Answers

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.

Doing a git revert makes new commits to remove old commits in a way that keeps everyone's history sane.

like image 72
Ben Jackson Avatar answered Sep 26 '22 07:09

Ben Jackson