Git 未跟踪文件
Stewart Nguyen
2022年4月22日
Git
Git Tracking
本文将介绍如何在 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