How to undo the last commit and discard the changes?

git reset --hard HEAD~1

To undo the last commit and discard the changes use git reset --hard HEAD~1.

The reset command resets your current HEAD to a specific commit, without creating a new commit for the revert.

The --hard flag discards your reverted changes.

The HEAD~1 tells reset to go back 1 commit from your current state.

Layer 1
Terminal Example
git status
On branch main
nothing to commit, working tree clean
git reset --hard HEAD~1
HEAD is now at 9cfff18 Adding file.txt
git status
On branch main
nothing to commit, working tree clean

See git reset to learn more about it.

Last modified on November 30, 2021.

You might also like