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教程

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