Git 恢复单个文件的历史

有时候我们会在一个commit中包含多个文件的修改。

但是当只需要恢复其中一个文件的历史的时候,revert就不是那么好用了。


以下步骤可以帮你实现这个目的:

假设目前repo中有两个文件README 和b.txt

现在修改两个文件,同时附加一行内容,均为a。

现在我只想恢复b.txt的内容到没有添加a的状态。

步骤如下:

1. $ git log --pretty=oneline -2
be4a7bf7fbb010e058b9cfd604e3bcd2cb04795b add line a in both file
52b7b10c3aaa2acf278827a229d308cfcb0b1cb8 init

2. $ git reset 52b7b10 b.txt 【我们需要b.txt回到init的状态,复制init的commit SHA值52b7b10】
warning: LF will be replaced by CRLF in b.txt.
The file will have its original line endings in your working directory.
Unstaged changes after reset:
M       b.txt

3.$ git status 【查看下状态,会发现b.txt有两种状态,不用理会】
# On branch mytest
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       modified:   b.txt
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   b.txt
#

4. $ git checkout -- b.txt 【现在只需要把b.txt恢复到修改之前,也就是init的状态就可以了】
5.$ git status【再看下状态,和b.txt的内容】
# On branch mytest
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       modified:   b.txt
#

5.1$ cat b.txt
This is b.txt

6. $ git commit -m "revert b.txt to certain commit"【现在commit就可以了】
[mytest 47099c3] revert b.txt to certain commit
 1 file changed, 1 deletion(-)


参阅以下文章:

http://www.cnblogs.com/zhulin/archive/2012/06/09/2542785.html

http://www.dewen.org/q/11420/git+%E6%81%A2%E5%A4%8D%E5%8D%95%E4%B8%AA%E4%BF%AE%E6%94%B9%E6%96%87%E4%BB%B6






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章