git 恢复在本地删除了的文件(已rm+commit)
场景:
最近两天学习了一下如何使用git,如何恢复被删除的文件,已经rm和commit,然后尝试恢复已经删除了的文件,前提是已经写入git库,不然恢复不了
解决:
首先在git的目录下新建一个测试文件,123.txt,查看git状态
$ git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
123.txt
nothing added to commit but untracked files present (use "git add" to track)
--git add
$ git add 123.txt
warning: LF will be replaced by CRLF in 123.txt.
The file will have its original line endings in your working directory
--git commit
$ git commit -m "add 123.txt"
[master 2dc5f0d] add 123.txt
1 file changed, 4 insertions(+)
create mode 100644 123.txt
--再次查看git状态
$ git status
On branch master
nothing to commit, working tree clean
---------------------开始恢复
--查看状态
$ git status
On branch master
Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
deleted: 123.txt
no changes added to commit (use "git add" and/or "git commit -a")
--查看被删除的文件
$ git log --diff-filter=D --summary
commit 1050ef7d1bc4aca28443ce0c207a66b56e064d2e (HEAD -> master)
Author: William Meng <346633091@qq.com>
Date: Sun Aug 4 17:02:38 2019 +0800
rm 123.txt
delete mode 100644 123.txt
--可以看草被删除的123.txt文件的commit id为1050ef7d1bc4aca28443ce0c207a66b56e064d2e
$ git checkout 1050ef7d1bc4aca28443ce0c207a66b56e064d2e~1 123.txt
Updated 1 path from e3778cc
--查看状态
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: 123.txt
去git目录查看已经恢复刚刚删除的123.txt文件。