直接给命令:git stash pop 后面跟上 stash@{n} 即可恢复指定的那条 stash,并且会从栈中删除它 :
git stash pop stash@{n}
其中 n 是 git stash list 里显示的编号,从 0 开始,stash@{0} 是最新的一条 。
一、完整操作流程
# 1. 先查看所有 stash,确认要恢复哪条
git stash list
# stash@{0}: On main: WIP: 修改登录逻辑
# stash@{1}: On dev: WIP: 新增支付接口
# stash@{2}: On dev: WIP: 修复样式 bug
# 2. 恢复并删除 stash@{1}(第二条)
git stash pop stash@{1}
执行后,stash@{1} 的内容被应用到工作区,并且该条目从 stash 列表中移除 。
二、两个关键注意点
1. Shell 中 {} 要转义或用引号包裹
在 Zsh 等 shell 里,大括号可能被当作特殊符号解析,导致报错。保险写法:
git stash pop "stash@{1}" # 推荐:加引号
# 或
git stash pop stash@\{1\} # 转义大括号
2. 冲突时 stash 条目不会被删除
如果 pop 时发生冲突,Git 会保留该 stash 条目(防止代码丢失),你需要:
# 冲突后,手动解决冲突文件里的 <<<<<<< HEAD 标记
# 解决完后:
git add <冲突文件>
git stash drop stash@{1} # 手动删除该条目
三、更安全的做法:apply + drop 分两步
如果你不确定这次恢复一定能干净合并,强烈建议用 apply 代替 pop:
# 1. 先预览要恢复的 stash 内容
git stash show -p stash@{1}
# 2. 应用到工作区,但保留 stash 条目
git stash apply stash@{1}
# 3. 确认无误后,再手动删除
git stash drop stash@{1}
两者的核心区别 :
| 命令 | 应用改动 | 从栈中删除 |
|---|---|---|
git stash apply stash@{n} |
✅ | ❌ 保留 |
git stash pop stash@{n} |
✅ | ✅ 删除(冲突时例外) |
💡 如果你当初 stash 时有 staged 的内容(比如
git stash push -S),恢复时加--index参数可以重建当时的 staged/unstaged 状态:
git stash pop --index stash@{1}
四、速查
git stash list # 查看所有 stash
git stash pop stash@{1} # 恢复并删除第 2 条
git stash apply stash@{1} # 仅恢复,不删除
git stash drop stash@{1} # 手动删除第 2 条
git stash show -p stash@{1} # 预览第 2 条的具体改动
记住一个原则:拿不准就用 apply,确定无误再用 pop------这样即使恢复出问题,原 stash 还在,不会丢代码。