有時候我們會在一個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