Undo a Git commit





Luc B.



A common mistake in Git is to commit the wrong file or to include a file you didn't intend to in a commit. Fortunately, git reset allows resetting your commit history back to it's state prior to the commit.

Note that resetting differs from reverting. git reset resets your commit history back to a previous commit. git revert does not modify your commit history, but rather it adds a new commit that drops changes from specific commits.

Code Example

Pass a commit reference to git reset to rollback your commit history to that commit. Changes made since that commit will become unstaged changes.

# Undo the most recent commit
git reset HEAD~1

Here we use Git's tilde syntax to refer to a previous commit: HEAD refers to the most recent commit in the current branch, HEAD~1 is parent of this commit, HEAD~2 is the grandparent, HEAD~3 is the great grandparent, and so on.

In this example, all changes made after HEAD~1 will become unstaged changes.

More Examples

Reset and Delete Changes

If you want to reset to a previous commit and delete all changes that were made since that commit, use the --hard flag.

# Reset to previous commit and delete all changes
git reset --hard HEAD~1