Git Reset
git reset is the most direct and powerful way to undo changes in Git. It allows you to move your current branch pointer backward to a previous state, affecting one or more of the repository's internal "layers."
1. The Three Layers of Git
To understand Reset, you must understand the three places Git stores code:
- HEAD: The pointer to the last commit on your current branch.
- Index (Staging Area): Where files are prepared for the next commit.
- Working Directory: The actual files you see and edit in your IDE.
2. Reset Modes Comparison
| Mode | Moves HEAD? | Clears Index (Staging)? | Clears Working Dir? | Risk Level |
|---|---|---|---|---|
--soft | Yes | No | No | Low |
--mixed | Yes | Yes | No | Medium |
--hard | Yes | Yes | Yes | High (Extreme) |
Soft Reset (--soft)
Best for: Undoing a commit but keeping the work staged so you can commit again (e.g., to fix a commit message or combine commits).
git reset --soft HEAD~1Mixed Reset (--mixed) [Default]
Best for: Unstaging files you accidentally added with git add, while keeping your actual code changes safely in your working directory.
git reset HEAD filename.txtHard Reset (--hard)
Best for: "Wiping the slate clean" and returning to a known good state. Use with extreme caution: this will delete all unstaged and uncommitted work permenently.
git reset --hard <commit_hash>3. Before and After (Visualizing History)
When you perform a reset, the branch pointer moves. The commits that were "after" the reset point don't disappear immediately—they become Orphaned Commits.
- They won't show up in
git log. - They still exist in the Git database temporarily.
- You can find them using
git reflogif you need to recover them.
4. Common Workflows
Unstage a specific file
git reset <filename>Discard all local changes (Nuclear Option)
git reset --hard HEAD[!CAUTION] Safety on Shared Branches Never use
git reset --hardon commits that have already been pushed to a shared repository. This "rewrites history" and will cause massive conflicts for your teammates. Usegit revertinstead for public history.