Git学习(九)--删除文件

转载廖雪峰的官方网站

删除文件

在Git中,删除也是一种修改,先添加一个test.txt文件到Git并提交

1
2
3
4
5
$ git add test.txt
$ git commit -m "add test.txt"
[master 3f4eef2] add test.txt
1 file changed, 1 insertion(+)
create mode 100644 test.txt

一般情况下,你可以直接在文件系统中将其删除,或者使用rm命令删除

1
rm test.txt

这个时候工作区和版本库的就不一致了,git status命令就会告诉你删除了哪些文件

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")

现在你有两个选择
​ 1.确实需要将版本库中的文件删除(使用git rm <file>...在进行git commit提交)
​ 2.误删了,需要将版本库的test.txt还原(使用git checkout -- <file>)

1
2
3
4
5
6
$ git rm test.txt
rm 'test.txt'
$ git commit -m "delete test.txt"
[master 894d519] delete test.txt
1 file changed, 1 deletion(-)
delete mode 100644 test.txt

另一种情况是删错了,因为版本库里还有呢,所以可以很轻松地把误删的文件恢复到最新版本:

1
$ git checkout -- test.txt

git checkout其实是用版本库里的版本替换工作区的版本,无论工作区是修改还是删除,都可以“一键还原”。

小结

命令git rm用于删除一个文件。如果一个文件已经被提交到版本库,那么你永远不用担心误删,但是要小心,你只能恢复文件到最新版本,你会丢失最近一次提交后你修改的内容