GIT学习----第七节:删除文件

学习目的

1.如果用rm命令删除文件,想要恢复,如何处理?
2.如果用git rm命令删除文件,想要恢复,如何处理?
3.如果彻底删除版本库的该文件,如何处理?

rm 删除文件

  1. 查看工作区状态
1
2
3
$ git status
On branch master
nothing to commit, working tree clean
  1. 使用 rm 命令删除文件test.txt
1
$ rm test.txt

此时删除的是工作区的test.txt文件,但是暂存区的test.txt文件未删除,如果删除错误希望恢复,如何处理?

  1. 工作区的文件误删恢复命令 git checkout –
1
2
3
4
5
6
7
8
9
$ 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: test.txt

no changes added to commit (use "git add" and/or "git commit -a")

查看工作区状态,告诉我们,test.txt 文件被删除,现在有两个选择,1:如果是误删,则使用 git checkout – 命令恢复工作区的误删文件;2:如果没有误删文件,则使用git rm 删除暂存区的该文件,同时用git commit -a命令提交到当前分支。

3.1 误删恢复

1
$ git checkout -- test.txt

3.2 非误删,删除版本库中该文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ git rm test.txt
rm 'test.txt'

$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)

deleted: test.txt

$ git commit -m "删除test.txt"
[master c1227ae] 删除test.txt
1 file changed, 1 deletion(-)
delete mode 100644 test.txt

git rm 删除文件

1
2
3
4
5
6
7
8
9
$ git rm test.txt
rm 'test.txt'

$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)

deleted: test.txt

git status 提示我们可以使用 git reset HEAD 还原。

1
2
3
4
5
$ git reset HEAD test.txt
Unstaged changes after reset:
D test.txt

$ git checkout -- test.txt

由于使用git rm命令不但删除了test.txt文件,同时将该删除操作提交到了暂存区,所以我们需要git reset HEAD 将暂存区的该文件撤回上个版本,同时需要git checkout – 将工作区的版本替换为暂存区的版本。

彻底删除

1
2
3
4
5
6
7
$ git rm test.txt
rm 'test.txt'

$ git commit -m "彻底删除test.txt"
[master 2b66c80] 彻底删除test.txt
1 file changed, 1 deletion(-)
delete mode 100644 test.txt

小结

  1. 工作区的文件误删(rm命令)恢复处理:git checkout –
  2. 暂存区的文件误删(git rm命令)恢复处理:1、git reset HEAD ;2、git checkout –
  3. 彻底删除处理:1、git rm ;2、git commit -m “提交说明”。
  4. 彻底删除的恢复处理: 1、 git reset –hard “commit id”;2、git checkout –

其他

QQ交流群: 264303060

QQ交流群

我的博客,欢迎交流!

我的CSDN博客,欢迎交流!

微信小程序专栏

前端笔记专栏

微信小程序实现部分高德地图功能的DEMO下载

微信小程序实现MUI的部分效果的DEMO下载

微信小程序实现MUI的GIT项目地址

微信小程序实例列表

前端笔记列表

游戏列表