0
0
GitHow-ToBeginner · 3 min read

How to Revert Commit in Git: Simple Commands Explained

To revert a commit in Git, use git revert <commit-hash> to create a new commit that undoes the changes. Alternatively, use git reset to move the branch pointer back, but be careful as it can rewrite history.
📐

Syntax

git revert <commit-hash>: Creates a new commit that reverses the changes made by the specified commit without changing history.

git reset [--soft|--mixed|--hard] <commit-hash>: Moves the current branch to the specified commit. --soft keeps changes staged, --mixed keeps changes unstaged, and --hard discards changes.

bash
git revert <commit-hash>
git reset [--soft|--mixed|--hard] <commit-hash>
💻

Example

This example shows how to revert the last commit safely using git revert. It creates a new commit that undoes the previous one.

bash
git log --oneline -3
# Output shows last 3 commits with hashes

# Suppose last commit hash is abc123

git revert abc123

# Git opens editor to confirm commit message
# Save and close editor to complete revert

git log --oneline -3
Output
abc123 Fix typo in README b7f9d2 Add new feature 4e3a1c Initial commit [Revert "Fix typo in README"] b8d4f1 Revert "Fix typo in README" abc123 Fix typo in README b7f9d2 Add new feature
⚠️

Common Pitfalls

  • Using git reset --hard can permanently delete uncommitted changes and commits if pushed, so use it carefully.
  • git revert is safer for shared branches because it does not rewrite history.
  • Always check the commit hash before reverting or resetting to avoid mistakes.
bash
## Wrong way (dangerous on shared branches):
git reset --hard abc123

## Right way (safe for shared branches):
git revert abc123
📊

Quick Reference

CommandDescriptionUse Case
git revert Creates a new commit that undoes changesSafe undo on shared branches
git reset --soft Moves branch pointer, keeps changes stagedUndo commits but keep changes ready to commit
git reset --mixed Moves branch pointer, keeps changes unstagedUndo commits and unstage changes
git reset --hard Moves branch pointer and discards changesDangerous: resets history and working directory

Key Takeaways

Use git revert to safely undo commits without rewriting history.
git reset changes branch history and can discard changes; use with caution.
Always verify commit hashes before reverting or resetting.
Prefer git revert on shared branches to avoid conflicts.
Understand the difference between --soft, --mixed, and --hard reset options.