Advertisement
Advertisement


Throw away local commits in Git


Question

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
2019/02/01
1
1548
2/1/2019 9:35:15 PM

Accepted Answer

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.

2019/04/30
2575
4/30/2019 3:01:13 PM

Simply delete your local master branch and recreate it like so:

git branch -D master
git checkout origin/master -b master
2011/02/23

Try:

git reset --hard <the sha1 hash>

to reset your head to wherever you want to be. Use gitk to see which commit you want to be at. You can do reset within gitk as well.

2014/04/28

Delete the most recent commit:

git reset --hard HEAD~1

Delete the most recent commit, without destroying the work you've done:

git reset --soft HEAD~1

2018/02/11

If you are using Atlassian SourceTree app, you could use the reset option in the context menu.

enter image description here

2015/01/29

On your branch attempt:

git reset --hard origin/<branch_name>

Validate the reversal (to the state, with no local commits), using "git log" or "git status" hence.

2016/03/31

Source: https://stackoverflow.com/questions/5097456
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]