git reset --hard explained (soft vs mixed vs hard)
git reset moves your branch to another commit. The --soft, --mixed and --hard flags decide what happens to your staged and working changes, and --hard is the one that actually throws work away.
- What git reset does
- Undo the last commit, keep the work
- Discard everything with --hard
- Recovering after a --hard reset
What git reset does
git reset moves the current branch tip to a commit you choose. The flag controls how far the reset reaches:
--soft: move the branch, keep everything staged.--mixed(the default): move the branch, unstage changes, keep them in your working directory.--hard: move the branch and discard all staged and working-directory changes.
Undo the last commit, keep the work
To undo your most recent commit but keep the changes so you can re-commit them, use --soft or the default --mixed:
git reset --soft HEAD~1 # commit undone, changes still staged
git reset HEAD~1 # commit undone, changes unstaged but present
Discard everything with --hard
--hard resets the branch and wipes uncommitted changes. Use it when you genuinely want to throw work away:
git reset --hard HEAD # discard all uncommitted changes
git reset --hard HEAD~1 # delete the last commit and its changes
A common use is forcing your local branch to match the remote exactly:
git fetch origin
git reset --hard origin/main
This is destructive. Anything not committed is gone. If you only want to clean up untracked files (not reset tracked ones), use git clean instead.
Recovering after a --hard reset
If you reset away a commit you actually needed, it is usually still findable for a while. git reflog records where HEAD has been:
git reflog
git reset --hard <commit-hash-from-reflog>
Note that reflog only recovers committed work. Changes that were never committed and got discarded by --hard cannot be recovered. When in doubt, stash your changes instead of resetting.