Git Revert
git revert is the safe way to undo changes in Git, especially when working on a team. Unlike commands that rewrite history, git revert adds to it.
🛡️ Why Revert is Safe
In a collaborative environment, rewriting history (using reset) can cause massive problems for teammates. git revert is the professional standard for undoing changes on shared branches because:
- It creates a new commit that is the exact opposite of the one you want to undo.
- It preserves project history, providing a trail of why something was undone.
- It doesn't delete anything, making it much safer and easier to track.
1. How it Works (The Anti-Commit)
Think of a revert as an "Anti-Commit." If a commit added a line, the revert commit will remove it. If a commit deleted a file, the revert commit will restore it.
Core Workflow
- Find the Commit Hash: Locate the ID of the commit you want to undo.
git log --oneline - Execute the Revert:
git revert 1a2b3c4 - Commit Message: Git will automatically open an editor with a message like
Revert "Added new login logic". Save and close to finish.
2. Comparison: Revert vs. Reset
| Feature | git revert | git reset |
|---|---|---|
| Action | Creates a new "undo" commit. | Moves the branch pointer backward. |
| History | Safe. Appends to history. | Dangerous. Deletes history. |
| Best For | Public/Shared branches (Main, Dev). | Local/Private feature branches. |
| Risk | Low. No work is ever lost. | High. Uncommitted work can be deleted. |
3. Handling Multiple Commits
You can revert more than one commit at a time, but be careful of conflicts:
- Revert the last commit:
git revert HEAD - Revert a range:
git revert old_hash..new_hash - Revert without immediate commit:
git revert -n <hash>(Applies changes to staging but waits for you to commit).
4. Resolving Conflicts
If a revert fails due to overlapping changes made after the target commit:
- Fix the conflicts manually.
git add <file>git revert --continue
[!TIP] DevOps Best Practice In a CI/CD pipeline, if a deployment fails, always revert rather than reset. This ensures the failed state and the fix are both recorded in the logs for future auditing and root-cause analysis.