How to Use Git Reset: Syntax, Examples, and Tips
Use
git reset to undo changes in your Git repository by moving the current branch pointer. It can reset the index and working directory depending on the mode: --soft, --mixed, or --hard.Syntax
The basic syntax of git reset is:
git reset [--soft | --mixed | --hard] [commit]
Explanation:
commit: The commit hash or reference to reset to.--soft: Moves the branch pointer tocommitbut keeps changes staged.--mixed(default): Moves the branch pointer and resets the staging area but keeps working directory changes.--hard: Moves the branch pointer and resets both staging area and working directory tocommit, discarding changes.
bash
git reset [--soft | --mixed | --hard] <commit>
Example
This example shows how to undo the last commit but keep the changes staged using --soft. Then it shows how to unstage changes with --mixed and finally discard all changes with --hard.
bash
git log --oneline -1 # Output: abc1234 Last commit message git reset --soft HEAD~1 # Moves branch pointer back one commit, changes stay staged git reset --mixed HEAD # Unstages changes but keeps them in working directory git reset --hard HEAD # Discards all changes and resets to current commit
Output
abc1234 Last commit message
Common Pitfalls
Common mistakes when using git reset include:
- Using
--hardwithout backup, which permanently deletes uncommitted changes. - Confusing
git resetwithgit checkoutorgit revert. - Not specifying a commit, which defaults to
HEADand may not do what you expect.
Wrong way (dangerous):
git reset --hard HEAD~1
This deletes changes permanently. Use carefully.
Right way to keep changes staged:
git reset --soft HEAD~1
Quick Reference
| Option | Effect |
|---|---|
| --soft | Move HEAD, keep changes staged |
| --mixed | Move HEAD, unstage changes (default) |
| --hard | Move HEAD, discard all changes |
Key Takeaways
Use git reset to move the branch pointer and control staged and working directory changes.
--soft keeps changes staged, --mixed unstages them, --hard discards all changes.
Be very careful with --hard as it deletes uncommitted work permanently.
Always specify the commit to reset to avoid unexpected results.
git reset is different from git revert; reset changes history, revert adds new commits.