The Challenge
You’ve made one or more commits locally that you want to undo. How can you effectively reverse these commits without losing your work?
Solutions
- Using
git reset
to Undo Commits Thegit reset
command allows you to move your branch pointer to a previous commit. a. Soft Reset (keeps changes staged):
git reset --soft HEAD~1 # Undo last commit
b. Mixed Reset (default, unstages changes):
git reset HEAD~1 # Undo last commit and unstage changes
c. Hard Reset (discards changes):
git reset --hard HEAD~1 # Undo last commit and discard changes
To undo multiple commits, replace 1
with the number of commits to undo.
- Preserving History with
git revert
If you want to keep a record of the undo action:
git revert HEAD # Creates a new commit that undoes the last commit
- Recovering from Hard Reset If you’ve used
git reset --hard
and need to recover:
git reflog # View recent actions
git checkout -b recovery-branch <commit-hash> # Create a new branch at the lost commit
Best Practices and Tips
- Always use
git log
to confirm which commits you’re undoing. - For collaborative branches, prefer
git revert
overgit reset
to maintain history. - Use
git stash
to temporarily save uncommitted changes before resetting. - Remember that
git reflog
entries expire after 90 days by default.
Example Workflow
- Undo last commit, keeping changes staged:
git reset --soft HEAD~1
# Make additional changes if needed
git commit -m "New commit message"
- Undo multiple commits and recommit:
git reset HEAD~3 # Undo last 3 commits
git add .
git commit -m "New commit combining previous work"
By understanding these techniques, you can confidently manage your local commit history and recover from mistakes in Git.
Would you like more information on any specific aspect of undoing commits in Git?