Throw away local commits in Git

483    Asked by KarenGrant in Data Science , Asked on Jul 14, 2021

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

Answered by Dylan Forsyth

If you can see only the excess commits you can just do

  git reset --hard origin/

To move back to the origin. This will reset the state of the repository to the previous commit and discards all changes.

If you want to make new commits to remove old commits in a way that keeps everyone's history will be the same. this can be done using

  git revert

Why git discard local commits?

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 the same.



Your Answer

Interviews

Parent Categories