How to revert a range of commits with one single revert commit
If you want to revert commit range B to D (at least in git version 2) in a single commit, you can do:
git revert -n B^..D
git commit -m "revert the commit range B to D, inclusive"
The -n
(or --no-commit
) argument tells git to revert the changes done by the commits starting from B's parent commit (excluded) to the D commit (included), but not to create any commit with the reverted changes. The revert only modifies the working tree (your active file system) and the index (your staged file section).
Don't forget to commit the changes after running git revert -n
:
git commit -m "revert the commit range B to D, inclusive"
You can also revert multiple unrelated commits in a single commit, using the same method. For example: to revert B and D but not C:
git revert -n B D
git commit -m "Revert commits B and D"
References:
https://www.kernel.org/pub/software/scm/git/docs/git-revert.html
Thanks Honza Haering for the correction.
From man git revert
:
-n
, --no-commit
Usually the command automatically creates some commits with commit log messages stating which commits were reverted. This flag applies the changes necessary to revert the named commits to your working tree and the index, but does not make the commits. In addition, when this option is used, your index does not have to match the HEAD
commit. The revert is done against the beginning state of your index.
This is useful when reverting more than one commits' effect to your index in a row.