Sometimes you want to obliterate your Git history as though it never happened. Maybe this is one day in the life of a software developer that you'd rather forget.
In this scenario, Mrs Peel has just told you that John's done some changes that make your work redundant. So your last two commits are not needed at all, and the rest of the changes on your local machine just aren't needed.
Using git reset --hard will wipe out the commits you want to delete and the working files that you have. Please think carefully before you use this!
The One Line Fix
This command deletes the last two commits, and all of your working files. For more cautious solutions, look further below.
The Git reset command will copy the last commit hash to a file called .git/ORIG_HEAD if you want to remind yourself of it another time:
Or use this, which has the identical effect:
Just Deleting Your Working Files
This command wipes out all your working files and the index, without affecting your commits:
Keeping a Backup
You can keep a backup in two ways. Firstly you can put a copy of your working files in stash:
And this command creates a new branch called my-rewind. It doesn't have the latest two commits on the main branch, but is otherwise the same.
So your main branch will continue to have those two commits, until you delete the branch later on. Much safer:
git checkout -b my-rewind HEAD~2
Recovering Deleted Commits
This can get you out of a lot of trouble. It won't replace any working files you've deleted, but this will roll back the last commands that have affected your branches.
It does this by telling the git reflog to go back to its penultimate state, thereby undoing the effect of the previous command you carried out, the reset on the branch.
It's an irony that the undo for a hard reset, is... a hard reset. In fact, this command can undo many actions that you take on a branch. Commits, check outs and cherry picks.
But for now, this will simply undo your branch reset action:
But if you want to save the most time, try a free for any use Git client
. It might be the best move you'll ever make with Git.