如何恢复被删除(drop)的 stash
恢复被 drop/clear 的 stash:git fsck --unreachable 找孤立提交,逐个 git show 确认后用 git stash apply <哈希> 恢复。时间窗口有限(gc 前),重要改动应尽早转成分支。
被 drop 的 stash 在垃圾回收前还能找回:stash 本质是提交对象,删除只是去掉引用。用 git fsck --unreachable(或 --lost-found)列出孤立提交,逐个 git show 确认,找到后 git stash apply <哈希> 恢复。
恢复流程
# 1. 找孤立提交(stash 的提交通常有多个父节点)
git fsck --unreachable 2>/dev/null | grep commit
# 2. 逐个确认内容
git show <哈希> --stat
# 3. 确认是它之后恢复
git stash apply <哈希>
缩小搜索范围
# 按提交日期倒序查看孤立提交(不自动限制为一周)
git fsck --unreachable | grep commit | cut -d' ' -f3 | while read h; do echo "$h $(git show -s --format='%ci %s' $h)"; done | sort -r | head
stash 提交的提交信息形如 "WIP on main: ...",含你 stash 时的 -m 备注,按说明关键词筛更快。
预防比恢复重要
- 重要改动别长期躺 stash:
git stash branch 分支名转正式分支; stash clear前务必stash list过一遍;- 超过一天还用不到的 stash,提交到 wip 分支推上去。
常见问题(FAQ)
Q:多久之内能找回?
能否恢复取决于对象是否仍在、reflog 和垃圾回收设置。gc.pruneExpire 常见默认值是两周,但它不是误删后的保证恢复窗口;不要主动运行 prune 或 gc,尽早检查对象。
Q:apply 回来的 stash 哈希和原来一样吗?
apply 会把对象中的改动应用到工作区,不会自动新增 stash 列表条目。若确认该对象确实是 stash,可另用 git stash store <哈希> 重新加入列表。
Q:gc 已经跑过了还有救吗?
Git 层面没了。只能从文件系统恢复(回收站、磁盘恢复工具)或其他机器上的克隆里找。