git rm 命令
简介
git rm 是 Git 中用于从 Git 仓库和工作区删除文件的命令。它同时删除文件并暂存删除操作。
基本概念
Git Rm vs 普通 Rm
| 特性 |
Git Rm |
普通 Rm |
| 工作区 |
删除文件 |
删除文件 |
| 暂存区 |
自动暂存删除 |
需要手动添加 |
| 操作 |
删除 + 暂存 |
只删除文件 |
命令语法
1 2 3 4 5 6 7 8
| git rm <文件>
git rm -r <目录>
git rm --cached <文件>
|
查看帮助文档
常用选项
| 选项 |
说明 |
-f, --force |
强制删除(即使文件已修改) |
-r, --recursive |
递归删除目录 |
--cached |
只从暂存区删除,保留工作区文件 |
-n, --dry-run |
预览模式,不实际删除 |
-q, --quiet |
静默模式 |
--ignore-unmatch |
如果文件不存在也不报错 |
基本使用
1. 删除文件
1 2 3 4 5 6
| $ git rm file.txt
$ git status
|
2. 删除目录
1 2 3 4 5
| $ git rm -r directory/
$ git rm -r directory
|
3. 只从 Git 删除(保留文件)
1 2 3 4 5 6
| $ git rm --cached file.txt
$ git rm --cached sensitive-file.txt $ echo "sensitive-file.txt" >> .gitignore
|
4. 强制删除
5. 预览删除
实际应用场景
场景1:删除不需要的文件
1 2 3 4 5
| $ git rm unwanted-file.txt
$ git commit -m "Remove unwanted file"
|
场景2:从 Git 中移除但保留文件
1 2 3 4 5 6 7 8 9
| $ git rm --cached file.txt
$ echo "file.txt" >> .gitignore
$ git add .gitignore $ git commit -m "Stop tracking file.txt"
|
场景3:批量删除
1 2 3 4 5
| $ git rm file1.txt file2.txt file3.txt
$ git rm *.log
|
场景4:删除目录
1 2 3 4 5
| $ git rm -r old-directory/
$ git commit -m "Remove old directory"
|
常见问题和解决方案
问题1:文件已修改无法删除
错误信息:
1
| error: the following file has local modifications
|
解决方案:
1 2 3 4 5 6 7
| $ git rm -f file.txt
$ git add file.txt $ git commit -m "Update file" $ git rm file.txt
|
问题2:只想从 Git 中移除
解决方案:
1 2 3 4
| $ git rm --cached file.txt
|
问题3:误删文件
解决方案:
1 2 3 4 5
| $ git checkout HEAD -- file.txt
$ git restore file.txt
|
最佳实践
1. 删除后立即提交
1 2 3 4 5
| $ git rm file.txt
$ git commit -m "Remove file"
|
2. 使用 –cached 移除跟踪
1 2 3 4
| $ git rm --cached file.txt $ echo "file.txt" >> .gitignore $ git commit -m "Stop tracking file.txt"
|
3. 预览删除
总结
git rm 是从 Git 仓库删除文件的命令:
- 删除文件:
git rm file 删除文件
- 删除目录:
git rm -r dir 递归删除
- 移除跟踪:
git rm --cached file 只从 Git 移除
- 强制删除:
git rm -f file 强制删除
关键要点:
- ✅ 使用
git rm 而不是普通 rm
- ✅ 删除后记得提交
- ✅ 使用
--cached 移除跟踪但保留文件
- ✅ 删除前可以预览