How do I undo the last commit in git?
Use git reset --soft HEAD~1 to undo the commit but keep the changes staged. Use git revert HEAD instead if the commit has already been pushed.
git reset --soft HEAD~1 # undo commit, keep changes staged
git reset HEAD~1 # undo commit, keep changes unstaged
git reset --hard HEAD~1 # undo commit AND discard the changes
git revert HEAD # new commit that undoes the last one#Which one to use
Not pushed yet, want to redo the commit: --soft. Your changes are still staged; commit again with a better message or split them up.
Just fixing the message: git commit --amend.
Forgot a file: stage it, then git commit --amend --no-edit.
Already pushed: git revert. It creates a new commit that undoes the old one, so history stays intact for everyone else.
#--hard discards work permanently
Anything not committed is gone. Before running it, consider git stash instead — it saves your changes and you can drop the stash later if you really did not want them.
#Recovering from a mistake
git reflog
git reset --hard abc1234reflog records every position HEAD has been in, including commits you "deleted". As long as it happened in the last 90 days, it is almost certainly recoverable.
#Undoing a file, not a commit
git restore path/to/file # discard working changes
git restore --staged path/to/file # unstage, keep changes