刪除檔案
回憶一下檔案的常見操作,新增檔案,修改檔案,刪除檔案等,新增和修改檔案都單獨討論過,現在我們來研究一下如何刪除檔案.
你可能會說刪除檔案還不簡單啊,直接 rm -rf <file>
即可,但是這僅僅是本地檔案被刪除了,對於 git
來說,檔案並沒有被刪除.
還記得我們開篇介紹git
時就說過,一切操作皆版本
,對於新增是一個版本,修改也是一個版本,就連刪除都是一個版本.
下面讓我們看一下 git
中如何刪除檔案吧!
背景
# 檢視當前檔案列表
$ ls
file1.txt file2.txt file3.txt newFile.txt test.txt
# 新建待刪除檔案
$ touch delete.txt
# 再次檢視當前檔案列表,確保新建檔案成功
$ ls
delete.txt file2.txt newFile.txt
file1.txt file3.txt test.txt
# 檢視當前檔案狀態: 新檔案 `delete.txt` 還沒被跟蹤
$ git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
.DS_Store
delete.txt
nothing added to commit but untracked files present (use "git add" to track)
# 新增新檔案 `delete.txt`
$ git add delete.txt
# 檢視檔案狀態: 已新增到暫存區,待提交到版本庫
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: delete.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
.DS_Store
# 提交新檔案 `delete.txt`
$ git commit -m "add delete.txt"
[master 7df386a] add delete.txt
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 delete.txt
# 再次檢視檔案狀態: 已經沒有新檔案 `delete.txt` 的更改資訊
$ git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
.DS_Store
nothing added to commit but untracked files present (use "git add" to track)
$
複製程式碼
以上操作,我們簡單建立 delete.txt
檔案,新增(git add
)並提交(git commit
) 該檔案,完成準備工作後,開始刪除檔案!
# 刪除前檔案列表
$ ls
delete.txt file2.txt newFile.txt
file1.txt file3.txt test.txt
# 刪除剛剛建立的檔案 `delete.txt`
$ rm delete.txt
# 刪除後檔案列表
$ ls
file1.txt file2.txt file3.txt newFile.txt test.txt
# 當前檔案狀態: `delete.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: delete.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
.DS_Store
no changes added to commit (use "git add" and/or "git commit -a")
$
複製程式碼
本地刪除 delete.txt
檔案後,再次檢視檔案狀態 git status
發現 git
給了我們兩條建議,其中一條 git checkout -- <file>
我們很熟悉,就是丟棄工作區的更改,此時此景下如果丟棄刪除操作,相當於撤銷刪除,難怪說刪除也是一個版本呢!
現在我們重點來看第一條建議 git add/rm <file>
,rm
是 remove
單詞的縮寫,即刪除檔案.
# 刪除檔案
$ git rm delete.txt
rm 'delete.txt'
# 檢視檔案狀態: `delete.txt` 檔案待提交
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
deleted: delete.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
.DS_Store
# 提交檔案
$ git commit -m "remove delete.txt"
[master 6298070] remove delete.txt
1 file changed, 0 insertions(+), 0 deletions(-)
delete mode 100644 delete.txt
# 再次檢視檔案狀態
$ git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
.DS_Store
nothing added to commit but untracked files present (use "git add" to track)
$
複製程式碼
刪除檔案和新增檔案類似,都是一次commit
,本地檔案的任何更改都要新增到暫存區,然後提交到版本庫.
小結
刪除檔案和新增檔案類似邏輯,git rm
刪除檔案後,依然需要 git commit
提交版本.