git revert
- Version
- 2.51
- Review
- Draft
Summary#
git revert creates a new commit that reverses the changes of an earlier one, leaving existing history in place. Reverting a merge also requires -m with the number of the parent to treat as the mainline.
Syntax#
git revert COMMIT
git revert --no-edit COMMIT
git revert -m 1 MERGE
git revert --abort
Example#
(
set -eu
scratch=$(mktemp -d "${TMPDIR:-/tmp}/devlookup-git.XXXXXX")
trap 'rm -rf -- "$scratch"' EXIT
unset GIT_CONFIG_GLOBAL $(git rev-parse --local-env-vars)
export GIT_CONFIG_NOSYSTEM=1 GIT_TEMPLATE_DIR= LC_ALL=C
export HOME="$scratch" XDG_CONFIG_HOME="$scratch" GIT_ATTR_NOSYSTEM=1
export GIT_PAGER=cat GIT_EDITOR=true
mkdir "$scratch/work"
cd "$scratch/work"
git init -q -b trunk
git config user.name "Reference Example"
git config user.email example@example.invalid
printf 'limit=10\n' > limits.txt
git add limits.txt
git commit -qm "Set limit"
git switch -q -c tuning
printf 'limit=0\n' > limits.txt
git commit -qam "Lower limit"
git switch -q trunk
git merge -q --no-ff -m "Merge tuning" tuning
# Parent 1 is the branch that received the merge.
git revert --no-edit -m 1 HEAD > /dev/null
git log -1 --format=%s
cat limits.txt
echo "commits: $(git rev-list --count HEAD)"
)
Expected output#
Revert "Merge tuning"
limit=10
commits: 4
Common mistakes#
Reverting a merge undoes its file changes but the merged commits remain ancestors, so merging that branch again does not bring them back. If later work fixes the original merged commits, revert the revert and then merge the fixes. If the branch was rebuilt from before the original merge, merge the rebuilt branch directly.
Version applicability#
Git 1.7.8 added revert --abort. Git 2.43 changed the default message used when you revert a revert commit.
The complete example requires Git 2.28 or later for git init -b.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0