git reset --hard HEAD~1
This command is useful for undoing the last commit and any changes made in the working directory and staging area, effectively reverting the repository to the state it was in before the last commit.
It operates by resetting the current branch's HEAD to the specified commit, in this case, one commit before the current HEAD, and discards all changes in the working directory and index.
The --hard
flag ensures that all changes in the working directory and index are discarded, making it a powerful but potentially dangerous command if used without caution. The HEAD~1
part specifies the commit to reset to, which is one commit before the current HEAD; this can be adjusted to HEAD~2
to go back two commits, or replaced with a specific commit hash.
Similar commands include git reset --soft HEAD~1
, which resets the commit history but keeps changes in the staging area, and git reset --mixed HEAD~1
, which keeps changes in the working directory but not in the staging area. For safer alternatives, git revert HEAD
can be used to create a new commit that undoes the changes of the last commit without altering the commit history.