Git 未跟蹤檔案

Stewart Nguyen 2022年4月22日 Git Git Tracking
Git 未跟蹤檔案

本文將介紹如何在 Git 中取消跟蹤檔案。

git 倉庫中的檔案有兩種狀態:已跟蹤未跟蹤

跟蹤檔案是 Git 知道的檔案。

未跟蹤檔案是已在工作倉庫中建立但尚未使用 git add 命令新增的檔案。

考慮這種情況。

cd ~ mkdir my-repo cd my-repo git init touch file.txt git add file.txt git commit -m 'First commit' 

Git 知道 file.txt,所以從技術上講,現在跟蹤 file.txt

稍後,你想通過將此檔名新增到 .gitignore 來告訴 Git 忽略 file.txt(或任何錯誤提交的檔案)

touch .gitignore echo 'file.txt' >> .gitignore git add .gitignore && git commit -m 'Ignore file.txt' 

會發生什麼?

提交 .gitignore 後,你對 file.txt 進行了更改,然後 git 仍然顯示 file.txt 被跟蹤,因為它仍然存在於你的倉庫索引中。

$ echo 'qwe' > file.txt $ git status On branch master Changes not staged for commit:  (use "git add <file>..." to update what will be committed)  (use "git restore <file>..." to discard changes in working directory) modified: file.txt  no changes added to commit (use "git add" and/or "git commit -a") 

在 Git 中取消跟蹤檔案

第一步,執行以下命令。

$ git rm --cache file.txt rm 'file.txt' $ git st On branch master Changes to be committed:  (use "git restore --staged <file>..." to unstage) deleted: file.txt 
  • rm 停止跟蹤並從本地倉庫目錄中刪除檔案。
  • --cache 選項指定 rm 命令僅從索引中刪除檔案,不從本地倉庫中刪除檔案

git rm --cache file.txt 將通過從倉庫索引中刪除 file.txt 來停止跟蹤它,但保持檔案完整。

$ git commit -m 'Remove file.txt from tracking' [master 4697164] Remove file.txt from tracking  1 file changed, 0 insertions(+), 0 deletions(-)  delete mode 100644 file.txt 

從現在開始,Git 不會跟蹤對 file.txt 所做的任何更改。

$ echo '123' > file.txt $ git st On branch master nothing to commit, working tree clean 
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

相關文章 - Git Tracking