git-revert - Linux


Overview

The git-revert command undoes the changes introduced by a single specified commit and adds a new commit that reverses those changes. It is used to revert commits when there are identified issues or when the code needs to be restored to a previous state.

Syntax

git revert [options] <commit>

Options/Flags

  • –no-commit: Do not create a new commit, instead create a new tree and index files.
  • –signoff: Sign the commit with Signed-off-by footer.
  • –edit: Let the user edit the commit message before committing.
  • –mainline: Only revert commits not on the current branch.
  • –cherry-pick: Only revert commits that exist in the current branch.

Examples

Simple revert:

git revert a1b2c3

Revert an older commit without creating a new commit:

git revert --no-commit HEAD

Revert a commit and open the commit message for editing:

git revert --edit d4e5f6

Revert a commit and sign the new commit with your name and email:

git revert --signoff 789abc

Common Issues

Cannot revert a merge commit:

Merge commits cannot be reverted directly. Instead, use git revert on the parent commits that introduced the problematic changes.

Integration

git-revert can be integrated with other commands like git cherry-pick and git rebase for complex undo operations.

Revert a commit on a different branch:

git checkout other-branch
git revert HEAD~2
git checkout main
git merge other-branch

Related Commands

  • git cherry-pick: Selectively apply commits from one branch to another.
  • git reset: Undo changes made to the working tree and index.