devroom.io/content/posts/2011-09-08-git-remove-reset-and-rollback-commits.md
2019-06-05 14:32:16 +02:00

43 lines
1.7 KiB
Markdown

+++
date = "2011-09-08"
title = "Git: remove, reset and rollback commits"
tags = ["git", "revert", "reset", "rollback"]
slug = "git-remove-reset-and-rollback-commits"
+++
We've all been there, you committed changes you now regret. If you didn't share those commits with anyone yet, you're safe. Let me show you how to remove commits from your local repository. I'll also include an example how to roll back commits you already did share with others.
~
Use `git log` to see your most recent commits. Let's say you want to revert the last three commits, you can run the following command:
``` shell
git reset --hard HEAD~3
```
If you only want the last commit to be removed:
``` shell
git reset --hard HEAD~1
```
HEAD~1 is a shorthand for the commit before head. But, it's also possible to roll back to a specific commit using the SHA hash.
``` shell
git reset --hard d3f1a8
```
> Please note that all your uncommitted changes will be lost when you perform `git reset --hard`. You might want to use [git stash][1] to save your uncommitted changes.
In case you already pushed your changes to a remote repository, you can't use `git reset`, because it will wreak havoc with other people's repositories later. Instead, you could revert your commit (e.g. create a new commit, undoing a previous one).
Note that git revert does not walk back into history, but only works on a specific commit or range of commits. To use my previous examples:
``` shell
git revert HEAD~3..HEAD
git revert HEAD~1..HEAD
git revert d3f1a8..master
```
Optionally specify the `--no-commit` option to see what's being reverted.
[1]: http://ariejan.net/2008/04/23/git-using-the-stash/