Git 删除文件

在Git中,删除也是一种修改的操作,我们验证一下,先在工作目录中添加一个新文件test.txt,并且提交:

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

        test.txt

nothing added to commit but untracked files present (use "git add" to track)

$ git add test.txt
$ git commit -m "测试删除效果"
[master 2f252e8] 测试删除效果
 1 file changed, 1 insertion(+)
 create mode 100644 test.txt

$ rm test.txt 删除文件或者去工作区里删除也可以

查看一下转态,git status马上就能告诉你哪些文件被删除

$ 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 checkout -- test.txt

2.第二种情况是,确实想从版本库中的删除该文件。那就用命令git rm删掉,并且commit

LV@LV-PC MINGW32 /c/gitrepository (master)
$ 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")

LV@LV-PC MINGW32 /c/gitrepository (master)
$ git rm test.txt
rm 'test.txt'

LV@LV-PC MINGW32 /c/gitrepository (master)
$ git commit -m "remove test.txt"
[master c4d239c] remove test.txt
 1 file changed, 1 deletion(-)
 delete mode 100644 test.txt

小结:

git rm 命令用于删除一个文件,如果一个文件被提交到版本库,那么你永远不用担心误删了。

但是要小心的是,你只能恢复文件到最新的版本,你会丢失最近一次提交后你修改的内容

原文地址:https://www.cnblogs.com/LvLoveYuForever/p/5512983.html