Undoing Changes in Git

Undoing Commits: Reset vs Revert vs Checkout

Git provides multiple ways to undo changes, each with different use cases:

git reset

Rewinds the branch pointer to a previous commit (destructive for unpublished changes)

# Soft reset (keeps changes staged)
git reset --soft HEAD~1

# Mixed reset (keeps changes unstaged - default)
git reset HEAD~1

# Hard reset (discards all changes)
git reset --hard HEAD~1

Warning: Only use --hard locally. Never reset published history.

git revert

Creates a new commit that reverses a previous commit (safe for shared branches)

# Revert a specific commit
git revert abc1234

# Revert the last commit
git revert HEAD

# Revert multiple commits
git revert abc1234..def5678

git checkout

Discards changes in working directory (doesn't affect commits)

# Discard changes to a file
git checkout -- filename

# Discard all unstaged changes
git checkout -- .

Amending Commits: Fixing the Last Commit

git commit --amend lets you modify the most recent commit:

Common Use Cases

# Add missed files to last commit
git add forgotten-file.js
git commit --amend --no-edit

# Change the commit message
git commit --amend -m "New commit message"

# Change both files and message
git add fixed-file.js
git commit --amend -m "Fixed implementation"

Amend Best Practices

  • Only amend unpublished commits
  • Use --no-edit to keep the same message
  • Avoid amending if commit was already pushed

Recovering Deleted Branches and Commits

Git's reflog tracks all reference changes, serving as a safety net:

Using git reflog

# View reflog (last 30 days by default)
git reflog

# Find lost commit
git reflog --all | grep "commit message"

# Restore deleted branch
git checkout -b recovered-branch abc1234

Recovery Workflow

  1. Identify the lost commit hash in reflog
  2. Create new branch pointing to it: git branch recovered abc1234
  3. Verify contents: git checkout recovered

Important Notes

  • Reflog entries expire after 90 days by default
  • Only local changes are tracked - remote branches need different recovery
  • For complex cases, use git fsck to find dangling commits

Finding Orphaned Commits

# Find dangling commits
git fsck --lost-found

# Inspect found commits
git show abc1234

Undo Cheatsheet

Situation Command
Undo uncommitted changes git checkout -- filename
Unstage staged changes git reset HEAD filename
Fix last commit message git commit --amend
Undo published commit git revert abc1234
Recover deleted branch git checkout -b branch abc1234

Post a Comment

0 Comments