无法在Git中恢复文件

9

可能重复:
在Git存储库中恢复已删除的文件

我在我的Git中有两个分支,master和newFeature。 在分支newFeature中,我首先在终端中物理删除了fileA,然后在Git中也进行了删除。

git rm fileA

随后,我运行

git add .
git commit

现在,我需要再次使用fileA文件。 我认为只需切换到分支master即可找回它。 然而,我错了,因为我无法找到fileA文件。

如何使用Git获取fileA文件?

3个回答

11

首先,您需要找到最新版本的fileA在哪里。您可以使用“git log -p”或“git whatchanged”来检查何时删除了它,或者您可以使用“git ls-files <revision> -- fileA”来检查文件是否存在于给定提交中,其中“<revision>”可以是masternewFeature^newFeature^表示newFeature的父级)。

然后,您需要使用以下任一方式将其检出:

$ git checkout <revision> -- fileA

或者重定向 "git show" 的输出

$ git show <revision>:fileA > fileA

不要忘记将文件添加到git中(如果需要)!


3
在删除fileA提交之前创建一个标签或分支,检出它,将fileA复制到其他地方,然后再次检出newFeature分支。其余步骤应该很简单。

2
你也可以在不创建分支的情况下使用 git checkout <commit hash>。 - Daniel Fanjul

1
@titan:~$ cd /tmp/
@titan:/tmp$ mkdir x
@titan:/tmp$ git init
Initialized empty Git repository in /tmp/.git/
@titan:/tmp$ echo a > a
@titan:/tmp$ git add a
@titan:/tmp$ git ci -m a
Created initial commit c835beb: a
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 a
@titan:/tmp$ git rm a
rm 'a'
@titan:/tmp$ git ci -m b
Created commit de97fae: b
 1 files changed, 0 insertions(+), 1 deletions(-)
 delete mode 100644 a
@titan:/tmp$ git whatchanged 
commit de97fae7a72375ffa192643836ec8273ff6f762b
Date:   Wed Mar 11 17:35:57 2009 +0100

    b

:100644 000000 7898192... 0000000... D  a

commit c835beb7c0401ec27d00621dcdafd366d2cfdcbe
Date:   Wed Mar 11 17:35:51 2009 +0100

    a

:000000 100644 0000000... 7898192... A  a
@titan:/tmp$ git show 7898192
a
@titan:/tmp$ git show 7898192 > a
@titan:/tmp$ 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接