1. 简介
在使用 Git 的过程中,我们经常需要临时保存当前的工作状态,这时候就会用到 git stash
。当我们想要恢复这些被保存的状态时,Git 提供了两个常用命令:git stash pop
和 git stash apply
。
虽然它们都能恢复之前保存的状态,但两者之间有一个关键区别:
✅ git stash apply
只是应用保存的状态,不会删除对应的 stash 条目;
❌ git stash pop
则是应用并删除对应的 stash 条目。
本文将详细对比这两个命令的使用方式与区别,帮助你选择更合适的操作。
2. 准备测试环境
为了更直观地演示两者的区别,我们先创建一个本地 Git 仓库进行测试。
2.1 初始化仓库
$ git init
创建一个测试文件:
$ echo "Hello World" > file.txt
添加并提交初始内容:
$ git add . && git commit -m "initial commit"
2.2 创建两个 stash 条目
第一次修改文件内容:
$ echo "Hello Baeldung" > file.txt
保存第一个 stash:
$ git stash push
Saved working directory and index state WIP on main: d344c10 initial commit
再次修改文件内容:
$ echo "Hello Git" > file.txt
保存第二个 stash:
$ git stash push
Saved working directory and index state WIP on main: d344c10 initial commit
查看当前的 stash 列表:
$ git stash list
stash@{0}: WIP on main: d344c10 initial commit
stash@{1}: WIP on main: d344c10 initial commit
现在我们有两个 stash 条目,可以开始对比 apply
和 pop
的行为差异了。
3. git stash apply
3.1 行为说明
git stash apply
会 应用指定的 stash 条目(默认是最新的一条),但 不会从 stash 列表中删除它。
执行默认应用:
$ git stash apply
On branch main
Your branch is up to date with 'origin/main'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: file.txt
no changes added to commit (use "git add" and/or "git commit -a")
查看文件内容是否恢复:
$ cat file.txt
Hello Git
✅ 成功应用了最新的 stash(stash@{0})的内容。
3.2 查看 stash 列表
$ git stash list
stash@{0}: WIP on main: d344c10 initial commit
stash@{1}: WIP on main: d344c10 initial commit
⚠️ 注意:stash 列表仍然存在,说明 apply
并不会删除 stash 条目。
4. git stash pop
4.1 行为说明
git stash pop
的行为与 apply
类似,但它会 在应用后自动删除该 stash 条目。
执行默认 pop:
$ git stash pop
On branch main
Your branch is up to date with 'origin/main'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: file.txt
no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (2dd4ffe4f0c000bf7a0b116cbf965ea0d91d601d)
查看文件内容是否恢复:
$ cat file.txt
Hello Git
✅ 成功应用了最新的 stash(stash@{0})的内容。
4.2 查看 stash 列表
$ git stash list
stash@{0}: WIP on main: d344c10 initial commit
⚠️ 注意:stash@{0} 已被删除,原来的 stash@{1} 现在变成了 stash@{0}。
5. 两者的核心区别
特性 | git stash apply |
git stash pop |
---|---|---|
是否删除 stash 条目 | ❌ 不删除 | ✅ 删除 |
可重复应用同一 stash | ✅ 支持 | ❌ 不支持(条目已删除) |
冲突处理方式 | 相同(停止执行,需手动解决) | 相同 |
可预测性 | ✅ 高(多次应用效果一致) | ⚠️ 低(每次应用不同条目) |
推荐使用场景 | ✅ 需要多次应用或保留 stash 时 | ✅ 确定不再需要该 stash 时 |
5.1 使用建议
- 如果你只是想恢复工作状态,且 不确定是否还需要保留 stash 条目,建议使用
git stash apply
。 - 如果你 确定该 stash 用完就不再需要,可以使用
git stash pop
,省去手动删除的步骤。 - 踩坑提醒:使用
pop
时要特别小心,一旦误删,虽然可以通过 reflog 恢复,但会增加不必要的麻烦。
6. 总结
git stash pop
和 git stash apply
的核心区别在于:
- ✅
apply
只应用不删除,适合保留 stash 多次使用; - ✅
pop
应用后立即删除 stash,适合一次性恢复。
如果你追求操作的可预测性和安全性,**优先使用 git stash apply
**;如果确认不需要保留 stash,再考虑使用 git stash pop
。
📌 小技巧:git stash pop
= git stash apply
+ git stash drop
,是一条组合命令。
合理使用这两个命令,可以让你在开发过程中更高效地管理临时保存的工作状态。