git add . 如果要去掉指定文件www/index.html,该用什么命令
已经执行了 git add .,想把某个文件撤出暂存区
bash
git restore --staged www/index.html
Git 2.23+ 的推荐写法。老版本没有 restore,用等价命令:
bash
git reset HEAD www/index.html
两者都只动暂存区,工作区里文件的改动不会被丢掉,文件会变回「未暂存」状态(git status 里显示为 modified)。想连带丢弃改动才需要 git checkout -- / git restore(不带 --staged),那一步要谨慎。
更省事的做法:一开始就别加进来
bash
git add . ':!www/index.html'
':!路径' 是 pathspec 排除语法,一次搞定。排除整个目录就用 ':!www/'。
如果这个文件根本不该进版本库
bash
echo "www/index.html" >> .gitignore
git rm --cached www/index.html # 只在索引里删除,本地文件保留
注意 git rm --cached 会生成一条「删除文件」的提交记录,而 git restore --staged 只是撤销暂存,不改历史。
三种命令对比
| 目的 | 命令 | 影响范围 |
|---|---|---|
| 撤销暂存,保留改动 | git restore --staged <file> |
仅索引 |
| 撤销暂存(老版本) | git reset HEAD <file> |
仅索引 |
| 从仓库移除但保留本地文件 | git rm --cached <file> |
索引 + 下次提交 |
| 撤销暂存 并 丢弃改动 ⚠️ | git restore <file> / git checkout -- <file> |
索引 + 工作区(不可恢复) |
补充一个易错的点:git reset HEAD <file> 在首次提交之前(仓库还没有任何 commit)会报 fatal: Failed to resolve 'HEAD',这种情况直接用 git rm --cached <file> 或 git restore --staged <file>。