情况1 将工作区的文件testfile.txt提交到本地库后删除
将testfile.txt文件提交到本地库:
$ git add testfile.txt
warning: LF will be replaced by CRLF in testfile.txt.
The file will have its original line endings in your working directory.
$ git commit -m "add testfile.txt" testfile.txt
warning: LF will be replaced by CRLF in testfile.txt.
The file will have its original line endings in your working directory.
[detached HEAD 242ee9f] add testfile.txt
1 file changed, 3 insertions(+)
create mode 100644 testfile.txt
从工作区删除testfile.txt文件:
$ rm testfile.txt
$ git status
HEAD detached from origin/python_exec
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: testfile.txt
no changes added to commit (use "git add" and/or "git commit -a")
将删除testfile.txt文件的操作添加到提交:
$ git rm testfile.txt
rm 'testfile.txt'
$ git status
HEAD detached from origin/python_exec
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
deleted: testfile.txt
将删除testfile.txt的操作提交到本地库:
$ git commit -m "delete testfile.txt"
[detached HEAD 080b52f] delete testfile.txt
1 file changed, 3 deletions(-)
delete mode 100644 testfile.txt
在工作区查看testfile.txt文件:
$ cat testfile.txt
cat: testfile.txt: No such file or directory
查看历史提交:
$ git reflog
080b52f (HEAD) HEAD@{0}: commit: delete testfile.txt
242ee9f HEAD@{1}: commit: add testfile.txt
通过git reset --hard [索引号]指令退回到删除testfile.txt文件之前的版本:
$ git reset --hard HEAD^
HEAD is now at 242ee9f add testfile.txt
再次从工作区查看testfile.txt文件:
$ cat testfile.txt
aaaaa
bbbbbbb
ccccccccc
情况2 将工作区的文件newfile.txt添加到暂存区后删除
将newfile.txt提交到本地库:
$ git add newfile.txt
warning: LF will be replaced by CRLF in newfile.txt.
The file will have its original line endings in your working directory.
$ git commit -m "add newfile.txt"
[detached HEAD c61a320] add newfile.txt
1 file changed, 4 insertions(+)
create mode 100644 newfile.txt
将newfile.txt文件从工作区删除:
$ rm newfile.txt
将删除newfile.txt的操作添加到提交但未提交到本地库:
$ git add newfile.txt
从工作区访问newfile.txt文件:
$ cat newfile.txt
cat: newfile.txt: No such file or directory
查看版本历史并退回到删除newfile.txt文件之前的一步:
$ git reflog
c61a320 (HEAD) HEAD@{0}: commit: add newfile.txt
$ git reset --hard HEAD 或者 git reset --hard c61a320
HEAD is now at c61a320 add newfile.txt
再次从工作区访问newfile.txt文件:
$ cat newfile.txt
aaaaa
xxxxxxxx
yyyyyyyyyyyyyyyyyy
提示 被删除的文件能够被找回的前提是文件的存在状态在删除之前已经被提交到本地库
|