Difference between git stash pop and git stash apply

Difference between git stash pop and git stash apply

技术背景

在使用 Git 进行版本控制时,有时我们在当前分支上进行了部分修改,但还未完成,此时需要切换到其他分支处理紧急任务。为了避免直接切换分支时产生冲突,我们可以使用 git stash 将当前的修改临时保存起来。之后再使用 git stash popgit stash apply 来恢复这些修改。

实现步骤

1. 临时保存修改

假设我们在 master 分支上工作,有一个文件 hello.txt 包含 “Hello” 字符串。我们对其进行修改,添加 “ world” 字符串。此时若要切换到其他分支处理问题,需要将这些修改临时保存:

1
git stash

2. 使用 git stash pop 恢复修改

当处理完其他分支的问题后,回到 master 分支,使用 git stash pop 恢复之前保存的修改:

1
git stash pop

如果此时查看 stash 列表,会发现之前保存的 stash 已经被移除:

1
2
$ git stash show -p
No stash found.

3. 使用 git stash apply 恢复修改

同样是在保存修改后,我们可以使用 git stash apply 来恢复修改:

1
git stash apply

之后查看 stash 列表,会发现之前保存的 stash 仍然存在:

1
2
3
4
5
6
7
8
$ git stash show -p
diff --git a/hello.txt b/hello.txt
index e965047..802992c 100644
--- a/hello.txt
+++ b/hello.txt
@@ -1 +1 @@
-Hello
+Hello world

核心代码

git stash pop

1
git stash pop

git stash apply

1
git stash apply

最佳实践

使用 git stash apply

当你不确定后续是否还需要再次使用这个 stash 时,建议使用 git stash apply。例如,你临时保存了一些实验性的修改,在恢复后还想保留这个 stash 以便后续参考或再次应用。

使用 git stash pop

当你确定不再需要这个 stash 时,使用 git stash pop 可以在恢复修改的同时清理 stash 列表,保持其简洁。例如,你保存了一些临时修改,在恢复后已经完全整合到当前工作中,不会再使用这个 stash。

常见问题

冲突问题

如果在执行 git stash popgit stash apply 时出现冲突,git stash pop 不会移除 stash,此时它的行为和 git stash apply 相同。需要手动解决冲突后,再根据情况决定是否使用 git stash drop 移除 stash。

误操作问题

由于很多人认为 stash 是一个简单的栈结构,使用 git stash pop 时可能会误以为 stash 已经被移除,从而在后续不小心再次弹出相同的 stash。为避免这种情况,在使用 git stash pop 前要确保自己确实不再需要这个 stash。


Difference between git stash pop and git stash apply
https://119291.xyz/posts/difference-between-git-stash-pop-and-git-stash-apply/
作者
ww
发布于
2025年5月28日
许可协议