Similar to unstaging, we occasionally may want to undo an entire commit. To clarify, when we say "undo a commit", we mean remove that commit from our history, and revert to the point at which the files were staged (with the changes captured in the commit).
The command used to undo a commit is:
git reset --soft HEAD^
To break this down,
HEAD refers to the current branch, and
HEAD^ means one commit back, aka the "parent commit". The
--soft here specifies that we should reset the branch (to point at that parent commit), but otherwise leave the files in the working directory and the index untouched.
This has the effect of undoing the commit, taking us back to just before we made it. Note that it leaves our changes staged in the index.
While useful, this is a complex command to remember, so once again we can create an alias, mapping this operation to the intuitive "uncommit" alias name.
git config --global alias.uncommit 'reset --soft HEAD^'
Occasionally we'll find that after making a round of changes, we realize that some of the changes are entirely unrelated to others.
Perhaps we've run
git add ., but we then realize that we only want to commit two of the three files that are now staged.
Once again, we can use a simple Git command to undo this.
git reset filename
To remove a particular file changes from working directory
git checkout filename
To remove all the changes from working directory
git checkout .
NOTE This is one of the few dangerous operations in Git. If you run
checkout without staging or committing your changes, Git will destroy your work and you will not be able to get it back. Be sure to use caution with
git checkout .!