Git教程:Git版本操作之删除文件(三)

删除文件

1、删除版本库中的某个文件:

例如,我们在仓库中新建一个文件 :testRemove.txt,写一句话Test how to delete file from Git repository,并提交至版本库,随后将其删除:

$ cat testRemove.txt
Test how to delete file from Git repository

$ git add testRemove.txt
$ git commit -m "Test delete"

首先在工作区删除文件: rm <fileName>, 然后Git会提示你工作区的目录和版本库的不一样,并且提醒你使用 git rm <fileName> 从版本库中彻底删除:于是乎,有了如下操作:

$ rm testRemove.txt

$ 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:    testRemove.txt

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

现在版本库提示你可以进行很多操作,就是有两种选择 1)确实是要从版本库删除,使用 git rm <fileName> ,就彻底删除了文件。2)放弃删除操作

$ git rm testRemove.txt
rm 'testRemove.txt'

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

	deleted:    testRemove.txt
	
$ git commit -m "remove testRemove"
[master 19ff64a] remove testRemove
 1 file changed, 1 deletion(-)
 delete mode 100644 testRemove.tx

可以看到已经彻底的删除了testRemove.txt 文件。

2)放弃删除。你可能只是脑子抽筋,错删了此文件,悔恨的拍大腿,但是,请记住Git总是有办法解决的。

因为你只是删除了工作区的文件,版本库中还依然存在,所以不用害怕。使用命令git checkout -- <file>即可:

$ git checkout -- testRemove.txt //注意:--与文件名之间的空格

$ ll             
total 20
drwxr-xr-x 3 codercxf codercxf 4096 123 15:59 ./
drwxr-xr-x 3 codercxf codercxf 4096 121 20:13 ../
drwxr-xr-x 8 codercxf codercxf 4096 123 15:59 .git/
-rw-r--r-- 1 codercxf codercxf  124 123 15:06 readme.txt
-rw-r--r-- 1 codercxf codercxf   44 123 15:59 testRemove.txt

看到testRemove.txt又回来了。

注意:这里的删除文件指的是删除版本库中的某一文件,在工作区(文件夹下的)直接删除即可(是无法恢复的)。

总结:
1、从版本库中删除文件:

第一步:在工作区删除文件 rm <file>

第二步:确定删除版本库中的文件: git rm <file> ,然后重新提交:git commit -m "确认删除文件描述"

2、如果已经在工作区删除,但是想恢复,此时版本库中该文件存在的,使用命令 git checkout -- <file> 即可以恢复原文件。


在这里插入图片描述




参考:
廖雪峰Git教程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章