如何 stash 未跟踪的新文件
git stash 默认不包含未跟踪文件,加 -u(--include-untracked):git stash -u;连 .gitignore 忽略的文件也要收用 -a(--all)。只收未跟踪文件可用 git stash push -u -- <路径>。
加 -u 参数:git stash -u(即 --include-untracked)——未跟踪的新文件连同已修改文件一起收进 stash。连 .gitignore 忽略的文件也要收(如本地构建产物),用 git stash -a。
用法
git stash -u # 已跟踪改动 + 未跟踪新文件
git stash -a # 再加上 gitignore 忽略的文件(罕见需求)
git stash -u -- src/new-file.js # 只收指定的未跟踪文件
验证
git stash show -p # 看 diff
git stash show -p --include-untracked # 部分版本需要显式 -u 才显示未跟踪内容
git stash pop / apply 恢复时,未跟踪文件会以未跟踪状态回来。
为什么默认不收未跟踪文件
stash 的内部实现基于提交对象,而未跟踪文件从未进过索引。-u 会让 Git 额外创建一个包含未跟踪文件的提交对象挂在 stash 记录里——所以收未跟踪文件的 stash 体积和创建时间都会略增。
常见问题(FAQ)
Q:node_modules 会被 -u 收进去吗?
不会——它在 .gitignore 里(-u 不碰忽略文件)。只有 -a 才会连忽略文件一起收,那通常不是你想要的。
Q:stash pop 后未跟踪文件与现有文件冲突?
恢复期间若同名文件已存在会报错。先把现有文件挪走再 pop。
Q:只想收未跟踪文件、不收已修改的?
git stash push -u -- <路径> 按路径限定即可精确控制。