Git reset vs git revert: Key Differences and When to Use Each
git reset command moves the current branch pointer to a previous commit, effectively removing commits from history, while git revert creates a new commit that undoes changes from a previous commit without altering history. Use git reset for local undo and git revert for safe undo in shared repositories.Quick Comparison
Here is a quick side-by-side comparison of git reset and git revert based on key factors.
| Factor | git reset | git revert |
|---|---|---|
| Effect on commit history | Moves branch pointer, removes commits | Adds a new commit that reverses changes |
| Safe for shared repos? | No, rewrites history | Yes, preserves history |
| Undo scope | Can undo multiple commits | Undo one commit at a time |
| Changes working directory? | Depends on mode (soft, mixed, hard) | No, only creates new commit |
| Use case | Local undo before pushing | Undo after pushing to shared repo |
| Command type | History rewrite | History preserving |
Key Differences
git reset changes the current branch pointer to a specified commit. This means commits after that point are removed from the branch history, which can cause problems if those commits were already shared with others. It has three modes: --soft (keeps changes staged), --mixed (keeps changes unstaged), and --hard (discards changes).
In contrast, git revert does not remove commits. Instead, it creates a new commit that reverses the changes introduced by a previous commit. This keeps the history intact and is safe to use on public branches. It is ideal for undoing changes after they have been pushed.
In summary, git reset rewrites history and is best for local fixes before sharing, while git revert preserves history and is best for undoing changes safely in shared environments.
Code Comparison
Example: Undo the last commit using git reset.
git reset --hard HEAD~1Git revert Equivalent
Example: Undo the last commit using git revert.
git revert HEAD
When to Use Which
Choose git reset when you want to undo commits locally before sharing your work, especially if you want to clean up or combine commits. Avoid using it on branches others use because it rewrites history.
Choose git revert when you need to undo changes that have already been shared with others. It safely adds a new commit that reverses changes without affecting the commit history.
Key Takeaways
git reset to undo commits locally by moving the branch pointer and optionally changing the working directory.git revert to safely undo changes by creating a new commit that reverses a previous commit.git reset rewrites history and is unsafe for shared branches; git revert preserves history and is safe for collaboration.git reset for cleaning up local commits before pushing.git revert to undo changes after commits are pushed to shared repositories.