git stash pop 与 git stash apply 的区别
两者都把 stash 的改动恢复到工作区,区别是:pop 应用成功后删除该 stash 条目,apply 保留条目。想重复应用同一 stash(比如到多个分支)用 apply;一次性恢复用 pop 更干净。
功能上都是"把 stash 的改动应用回工作区",唯一区别:成功后 pop 会把这条 stash 从列表里删除,apply 会保留。 所以 pop ≈ apply + drop。需要把同一份改动应用到多个分支时必须用 apply。
对照
git stash pop # = apply stash@{0} + 删除该条目
git stash apply # 应用 stash@{0},条目保留
git stash apply stash@{2} # 应用指定条目,保留
git stash drop stash@{2} # 只删除不应用
| pop | apply | |
|---|---|---|
| 应用改动 | ✅ | ✅ |
| 删除条目 | ✅(成功后) | ❌ |
| 冲突时 | 条目保留不删(安全) | 条目保留 |
为什么冲突时 pop 不删条目
pop 遇到合并冲突会应用失败(工作区留下冲突标记),此时不会删除 stash 条目——改动还有一份备份。解决完冲突、确认无误后自己 git stash drop。
常见用法
# 同一份改动要铺到多个分支
git checkout branch-a && git stash apply 'stash@{0}'
# 检查并提交或单独保存 branch-a 的恢复结果,确认工作区干净后再继续
git checkout branch-b && git stash apply 'stash@{0}'
# 同样检查并保存 branch-b 的结果
git stash drop stash@{0} # 最后手动清理
常见问题(FAQ)
Q:apply 之后改动进了暂存区还是工作区?
默认不保证重建原暂存/未暂存分离状态;新增文件和已有暂存状态仍可能导致部分内容已暂存。想恢复 stash 时的暂存/工作区分离状态,加 --index。
Q:pop 错分支了怎么办?
改动已经在工作区,先检查是否混入原有改动或冲突,分别保存;不能直接 stash 掩盖现场。冲突时原条目保留,但工作区已部分应用,并非原子回滚,也没有 stash --continue。
Q:stash 列表越来越乱怎么清理?
git stash list 检查,git stash drop stash@{n} 逐条删,或 git stash clear 清空全部(可能仅在对象未被回收前尝试找回,不可当作可靠恢复方式,慎用)。