如何恢复用“git rm *”删除的文件?

时间:2015-04-06 13:19:33

标签: git

我意外地使用git rm *删除了本地仓库第一次提交后的所有文件。

Git commit

git commit -m 'IF ELSE'
[master fc9895a] IF ELSE
 14 files changed, 3234 insertions(+)
 create mode 100644 Lecture 03 - Bootstrapping.ppt
 create mode 100644 Makefile
 create mode 100644 codegenerator.cpp
 create mode 100644 error.cpp
 create mode 100644 error.h
 create mode 100644 includelex.h
 create mode 100644 includeyacc.h
 create mode 100644 lexrule.l
 create mode 100644 rule.tab.c
 create mode 100644 stable.h
 create mode 100644 symboletable.cpp
 create mode 100644 test.c
 create mode 100644 yaccrule.y
 create mode 100644 yaccrule2.y

git rm *
rm 'Lecture 03 - Bootstrapping.ppt'
rm 'Makefile'
rm 'README.md'
rm 'codegenerator.cpp'
rm 'error.cpp'
rm 'error.h'
rm 'includelex.h'
rm 'includeyacc.h'
rm 'lexrule.l'
rm 'rule.tab.c'
rm 'stable.h'
rm 'symboletable.cpp'
rm 'test.c'
rm 'yaccrule.y'

我用来恢复的命令序列。

git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    deleted:    Lecture 03 - Bootstrapping.ppt
    deleted:    Makefile
    deleted:    README.md
    deleted:    codegenerator.cpp
    deleted:    error.cpp
    deleted:    error.h
    deleted:    includelex.h
    deleted:    includeyacc.h
    deleted:    lexrule.l
    deleted:    rule.tab.c
    deleted:    stable.h
    deleted:    symboletable.cpp
    deleted:    test.c
    deleted:    yaccrule.y
    deleted:    yaccrule2.y

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    .hg/


git reset --hard HEAD^1
HEAD is now at 9b72b0c first commit


git reset --hard HEAD
HEAD is now at 9b72b0c first commit


 git checkout
 Your branch is up-to-date with 'origin/master'.


 git reset HEAD test.c
 git reset HEAD  Makefile
 git reset HEAD --  Makefile

git status
On branch master
Your branch is up-to-date with 'origin/master'.
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    .hg/

我无法在Ubuntu 14.10,git 2.1.0版上恢复文件。 有没有办法让我可以恢复文件?

1 个答案:

答案 0 :(得分:2)

侦探工作

根据您对问题的描述,在遇到麻烦之前,您的回购历史必须包含两个提交:

9b72b0c first commit
fc9895a IF ELSE (HEAD, master)

证据

  • 有关第二次提交的信息位于

    的输出中
    git commit -m 'IF ELSE'
    
  • 的输出
    git reset --hard HEAD^1
    

    (此命令将当前分支重置为当前提交的)表示fc9895a的父级具有SHA 9b72b0c和消息first commit

将分支重置为所需状态

由于您在运行git rm *后尚未进行任何本地更改,因此您只需在执行IF ELSE提交后立即返回存储库所处的状态。< / p>

幸运的是,您仍然记录了该提交的简短SHA:fc9895a。因此,

git reset --hard fc9895a

是让你摆脱困境的命令。

解释

git-reset用于将当前分支(此处master)重置为指定的状态(fc9895a,此处)。

git-reset man page因此描述了--hard标志:

  

--hard

     

重置索引和工作树。自<commit>以来对工作树中跟踪文件的任何更改都将被丢弃。

(谨慎使用!)

Here很好地介绍了git-reset的工作原理。