git rm -r --cached_git 撤销对文件的追踪
撤销暂存区(index)区的track
当我们新增加文件时,使用git status会打印出:
1 2 3 4 5 6 7 | Untracked files: (use "git add <file>..." to include in what will be committed) hello.txt nothing added to commit but untracked files present (use "git add" to track) |
可见,git add 命令可以用来追踪文件。
当我们使用 git add hello.txt后,再使用git status后,会打印出:
1 2 3 4 5 | Changes to be committed: (use "git restore --staged <file>..." to unstage) new file: hello.txt |
可见,文件已经被追踪了,只是还没提交到本地仓库。此时可以使用git restore
来撤销这个追踪。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | > git restore hello.txt --staged > git status On branch master Your branch is up to date with 'origin/master' . Untracked files: (use "git add <file>..." to include in what will be committed) hello.txt |
撤销“已经提交到本地仓库的文件”的追踪
当一个文件(例如hello.txt)已经提交到本地仓库时。后续你再往.gitignore添加它,也不会起作用。怎么解除这种追踪呢?最常见的做法是直接删除这个文件,流程是:本地删除,提交删除这个commit到仓库。
但这样本地的也会被删除。有时我们只是想删除仓库的副本,可以使用git rm --cached
。git rm
经常被用来删除工作区和暂存区的文件。它可以携带一个cache参数,作用如下(摘自文档):
1 2 3 4 5 | git rm --cached Use this option to unstage and remove paths only from the index. Working tree files, whether modified or not, will be left alone. 使用这个项来解除暂存区的缓存,工作区的文件将保持不动。 |
意思就是不会在实际上删掉这个文件,只是解除它的追踪关系。
举例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | > git rm --cached hello.txt // rm 'hello.txt' > git status On branch master Your branch is up to date with 'origin/master' . Changes to be committed: (use "git restore --staged <file>..." to unstage) deleted: hello.txt |
工作区的hello.txt
还在,但已经没有被git追踪了。之后,只要我们把hello.txt
添加到.gitignore
后,修改hello.txt
并不会产生改动。
接下来我们提交下这个改动。
1 2 3 4 5 6 7 | git commit -m 'delete hello.txt' [master d7a2e3e] delete hello.txt 1 files changed, 17 deletions(-) delete mode 100644 hello.txt |
使用rm这个命令时,我们经常会用到-r这个命令。-r是递归的意思,表示删除整个文件夹,包括它的子文件夹。

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构