解决 Git 报错 fatal: reference is not a tree 的排查指南
排查与解决 Git 切换分支、检出提交或子模块更新提示 fatal: reference is not a tree 的完整方案。
问题现象
在 Git 仓库中执行 git checkout、git reset 或在持续集成构建中执行 git submodule update 时,命令报错退出:
fatal: reference is not a tree: d8a9f4c3b2e1...
Unable to checkout 'd8a9f4c3b2e1...' in submodule path 'libs/core'
触发根因
- 子模块指向的提交尚未推送远端:主工程引用了子模块的某个具体 Commit ID,但提交者在子模块中只完成了本地 commit,忘记将该子模块的代码
git push到子模块的远程仓库。CI/CD 或其他协作者拉取时找不到该提交哈希。 - 浅克隆(Shallow Clone)深度不足:在 CI/CD 中为了提速使用了
--depth 1,导致请求的历史 Commit 节点并未包含在本地浅克隆的对象树中。 - 拼写错误或该哈希并非一个合法的 Tree / Commit 对象。
解决步骤与操作命令
步骤一:子模块维护者在子模块中完成远程推送
如果是子模块引起的报错,让在子模块中提交代码的开发者进入子模块目录推送代码:
cd libs/core
git push origin $(git rev-parse --abbrev-ref HEAD)
步骤二:在 CI/CD 流水线中解除浅克隆限制
如果本地是浅层克隆,通过 unshallow 获取完整历史对象树:
git fetch --unshallow || git fetch --depth=100
更新子模块时允许拉取远端追踪分支:
git submodule update --init --recursive --remote
步骤三:验证目标哈希的对象类型
使用 git cat-file -t 检查该哈希是否为合法的 tree 或 commit:
git cat-file -t d8a9f4c3b2e1
若返回 fatal: git cat-file: could not get object info,说明本地确无该对象,必须运行 git fetch origin 同步。
验证确认
重新拉取完整对象后执行检出:
git submodule update --init --recursive
子模块顺利检出指定提交并成功同步,控制台无任何 fatal: reference is not a tree 报错。


