用 --shallow-since 比 --depth 更稳,因其按时间拉取提交,对 force-push 和历史重写更友好;--depth 1 易因远程新提交导致检出无效 commit,且缺失祖先提交使 git blame、checkout 等失败。

直接说结论:用 --shallow-since 比 --depth 更稳,尤其当仓库历史被重写或 CI 环境不稳定时。
为什么 --depth 1 经常出问题?
它只拉“最近一次提交”,但 Git 是按提交链工作的。浅克隆后:git log 只显示当前 HEAD 可达的提交,而父提交对象根本没下载,所以你查不到任何历史、切不了旧 tag、git blame 会报错找不到祖先。
- 执行
git clone --depth 1 https://github.com/xxx/repo.git后,git log --oneline确实只输出 1 行 —— 这不是 bug,是设计如此 - 如果远程在 clone 过程中推送了新 commit,
--depth 1可能检出一个“不存在于远程 ref 中”的 commit,导致后续git checkout失败 -
--depth默认启用--single-branch,你连origin/dev都看不到,除非手动git fetch --unshallow(但很多 CI 不允许)
--shallow-since="2 weeks ago" 怎么用?
它不数提交次数,而是按时间戳拉取所有“发生在指定时间之后”的提交,对 rebase、force-push 更友好,也更容易预估数据量。
- 命令示例:
git clone --shallow-since="2 weeks ago" https://github.com/elastic/elasticsearch.git - 时间格式支持:
"2026-04-01"、"last Monday"、"3 days ago",建议用相对时间避免硬编码日期 - 注意:必须加
--no-single-branch才能看到其他分支的最新提交(否则只拉默认分支) - 如果遇到
fatal: remote error: upload-pack: not our ref,说明某些 ref 已被 GC 或 force-push 清理,改用--shallow-exclude=<code>commit-hash排除坏引用
CI 场景下怎么让 shallow clone 不翻车?
CI 的并发、缓存、网络抖动会让基于深度或时间的浅克隆变得不可靠。更推荐用稀疏对象过滤替代。
- 用
git clone --filter=blob:none -b main --single-branch https://...,它不依赖提交链,只跳过二进制 blob,对历史变动完全免疫 - 在 CI 脚本开头加校验:
git cat-file -e $(git rev-parse origin/main) 2>/dev/null || git fetch --prune,防 ref 失效 - 不要依赖
git log默认行为;想看所有已拉取的提交,必须用git log --all --oneline -
git config advice.shallowUpdate false关掉自动修剪提示,否则 fetch 加深后 Git 会悄悄删掉你刚拉的提交
真正容易被忽略的点是:浅克隆后,git merge-base origin/main HEAD 这类依赖完整祖先链的操作会失效——不是命令错了,是你本地根本没那些 commit 对象。别急着骂 Git,先确认你要的操作是否真的需要完整历史。


















