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






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值