从 Git 历史中提取 LFS 管理的文件
场景
项目使用了 Git LFS 管理大文件(如图片),需要从某个历史提交中提取特定文件的原始内容。
常见误区
直接使用 git show 提取:
git show <commit>:<path> > output.png
如果文件由 LFS 管理,得到的只是一个 133 字节的 LFS 指针文件,内容类似:
version https://git-lfs.github.com/spec/v1
oid sha256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
size 12345678
正确做法
使用 git cat-file 配合 git lfs smudge:
git cat-file -p "<commit>:<path>" | git lfs smudge > output.png
git cat-file -p— 从指定提交中读取文件内容(LFS 指针)git lfs smudge— 根据指针从 LFS 存储中还原真实文件内容
完整示例
# 从提交 abc1234 中提取4个PNG文件
mkdir -p /tmp/output
for i in 1 2 3 4; do
git cat-file -p "abc1234:path/to/image_${i}.png" \
| git lfs smudge \
> "/tmp/output/image_${i}.png"
done
补充
- 前提是本地 LFS 缓存中有对应的文件对象,否则
git lfs smudge会尝试从远端下载 - 如果仓库没有使用 LFS,直接
git show <commit>:<path> > output即可

浙公网安备 33010602011771号