Whether you've made a mistake in your commit or simply want to modify it before pushing to a remote repository, undoing a git commit can be extremely useful. This guide covers several commands and steps you can follow ranging from completely removing a commit from your history, to undoing a commit nondestructively while retaining the changes.
Undo the last commit without discarding changes
To undo your most recent commit and keep all changes from that commit in your working directory, run:
git reset --soft HEAD~1
This command moves the current HEAD back one commit but keeps the changes in your staging area, allowing you to modify and recommit if needed.
Undo the last commit and discard changes
If you want to completely remove the last commit and all changes associated with it:
git reset --hard HEAD~1
This will reset your working directory and index (staging area) to the state of the commit before the last.
For further reading on how to properly use the --hard
flag see this guide on how to use git reset.
Undo multiple commits
To undo multiple commits without discarding any of the staged changes:
git reset --soft HEAD~N
Replace N
with the number of commits you wish to undo. This will not discard the changes you currently have staged.
If you want to completely clean the staging area and discard all changes from the last N
commits use the --hard
flag:
git reset --hard HEAD~N
Revert a commit
If you've already pushed your commit or want to undo a specific commit safely without rewriting history, git revert
is the right choice:
git revert <commit-hash>
This command creates a new commit that undoes the changes made by the commit you specify, preserving the project history.
Cleaning untracked files
After undoing commits, if you have untracked files you want to discard, or “clean”, run the command:
git clean -f -d
This removes untracked files and directories from your working tree, discarding them.
By default Git will refuse to delete files unless the -f
flag is specified.
The -d
flag instructs the clean
command to recurse into untracked directories, and the following subdirectories.
While not necessary, it is highly recommended to first do a “dry run” of the git clean
command by using the -n
flag. By including this flag clean
will not actually delete anything and instead return a list of all of the files that would be deleted when executing the command. Once you are satisfied with this output, remove the -n
flag and run the clean
command again to remove untracked files.
For further reading on how to undo Git commits please see the official Git documentation on git reset
and git revert