DevOps
Git
Git Reset

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:

  1. HEAD: The pointer to the last commit on your current branch.
  2. Index (Staging Area): Where files are prepared for the next commit.
  3. Working Directory: The actual files you see and edit in your IDE.

2. Reset Modes Comparison

ModeMoves HEAD?Clears Index (Staging)?Clears Working Dir?Risk Level
--softYesNoNoLow
--mixedYesYesNoMedium
--hardYesYesYesHigh (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~1

Mixed 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.txt

Hard 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 reflog if 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 --hard on commits that have already been pushed to a shared repository. This "rewrites history" and will cause massive conflicts for your teammates. Use git revert instead for public history.