Git:git-revert 的用法总结

概述

1
git-revert - Revert some existing commits // 撤销一些已经存在的提交 

博客

原文收藏于IT老兵驿站

语法

1
2
3
4
git revert [--[no-]edit] [-n] [-m parent-number] [-s] [-S[<keyid>]] <commit>…​
git revert --continue
git revert --quit
git revert --abort

理解

Given one or more existing commits, revert the changes that the related patches introduce, and record some new commits that record them. This requires your working tree to be clean (no modifications from the HEAD commit).
Note: git revert is used to record some new commits to reverse the effect of some earlier commits (often only a faulty one). If you want to throw away all uncommitted changes in your working directory, you should see git-reset[1], particularly the –hard option. If you want to extract specific files as they were in another commit, you should see git-checkout[1], specifically the git checkout syntax. Take care with these alternatives as both will discard uncommitted changes in your working directory.

这个工具的使用场景有一点复杂,所以把原本的介绍贴在这里,下面附上翻译:
给定一个或多个现有提交,还原由这些提交引入的更改,并用新的提交去记录。 这需要您的工作树是干净的(没有对于HEAD的修改)。注意:git revert用于记录一些新的提交以还原某些早期提交的效果(通常是一个错误的提交)。 如果你想丢弃工作目录中所有未提交的更改,你应该看到git-reset [1],特别是–hard选项。 如果你想在另一个提交中提取特定文件,你应该看到git-checkout [1],特别是git checkout <commit> - <filename>语法。 请注意这些替代方案,因为它们都会丢弃工作目录中未提交的更改。

意思是,如果你想撤销之前的一个或几个提交带来的修改,那么使用这个工具;如果想放弃工作目录的修改(并没有提交),那么你应该使用git reset;或者你只是想检出一个文件的某一个版本,那么使用git checkout

实例

摘录了官网的两个例子:
实例: 撤销 HEAD 指针之前的第3个提交,并且生成一个新的提交。这里补充解释一下,HEAD 是指当前的提交指针,除了 HEAD,再往前找3个,所以下面的英文里面说是第4个。

1
git revert HEAD~3

Revert the changes specified by the fourth last commit in HEAD and create a new commit with the reverted changes.

实例: 撤销从 master 之前第5个提交到之前第3个提交的变化(这么看来,前面是开区间,第6个没有被包含;后面是闭区间,包含了第3个,这个语法厉害了)。

1
git revert -n master~5..master~2

Revert the changes done by commits from the fifth last commit in master (included) to the third last commit in master (included), but do not create any commit with the reverted changes. The revert only modifies the working tree and the index.

实例: 撤销某个提交带来的修改

1
git revert <commit>

参考

https://git-scm.com/docs/git-revert