git revert
Safely undo commits by creating new commits that reverse their changes, preserving history.
A commit introduced a bug that made it to production, and you need to undo it
immediately. Unlike git reset, which rewrites history, git revert creates a
new commit that undoes a previous commit's changes while preserving the complete
history. This makes it safe to use on shared branches like main where rewriting
history would cause problems for your team.
Running git revert abc123 examines what changes that commit introduced, then
creates a new commit that reverses those changes. If the original commit added a
function, the revert commit removes it. If it modified a file, the revert undoes
those modifications. The result is that the code looks like the original commit
never happened, but both the original and the revert remain in history.
You can revert multiple commits with git revert abc123 def456, or a range with
git revert abc123..def456. Each reverted commit gets its own revert commit,
maintaining a clear record of what was undone and when. If you want to revert
several commits but create only one revert commit, use
git revert -n abc123 def456 (the -n flag means no commit), make any
additional changes, then commit manually.
When reverting creates conflicts—because the code has changed significantly
since the original commit—Git stops and asks you to resolve them. After
resolving and staging files, git revert --continue creates the revert commit.
If you decide reverting is too complicated, git revert --abort cancels the
operation.
In pull request workflows, revert is how you safely undo merged PRs. If a feature causes problems in production, you can revert the merge commit to quickly roll back, then investigate the issue at your own pace. The revert commit can be merged immediately for a quick fix, while you work on properly addressing the bug in a new PR. Some teams even create "revert PRs" to track the rollback through code review.
Understanding revert means having a safe undo button for commits on shared branches. It doesn't erase history—it adds to it with commits that reverse previous work. This transparency is valuable for understanding what happened and why, especially when debugging or conducting post-mortems on production issues.
