不使用Git reset 恢复误删除的 Git Submodule

This commit is contained in:
li-chx 2025-11-16 20:15:42 +08:00
parent c2459db584
commit 2865b12ed9
1 changed files with 48 additions and 0 deletions

View File

@ -0,0 +1,48 @@
---
{
title: "不使用git reset 恢复误删除的 submodule",
description: "这篇文章介绍了两种恢复误删除 Git Submodule 的方法:一种是使用 git reset 的简单方案,另一种是不使用 reset 的详细手动恢复步骤,帮助你在不改变提交历史的情况下修复子模块。",
draft: false,
type: "article",
created_at: "2025-11-16T16:34:11+08:00",
published_at: "2025-11-16T16:48:20+08:00",
updated_at: [ "2025-11-16T16:48:20+08:00" ],
category: '开发',
tags: [ "Git" ],
tech_stack: [ "Git" ],
tech_stack_percent: [ 1 ],
tech_stack_icon_names: [ "mdi:git" ],
tech_stack_theme_colors: [ "#f65f3d" ],
}
---
## 如果你可以使用Git Reset
如果你可以使用 `git reset`,那么恢复误删除的 Git Submodule 非常简单:
```bash
git reset --hard HEAD
git submodule update --init --recursive
```
## 如果不能使用Git Reset
如果你不能使用 `git reset`只想重新checkout误删除的Git Submodule可以使用以下方法
这里我使用example作为submodule名字和路径`.gitmodules` 配置如下:
```
[submodule "example"]
path = example
url = https://github.com/example/example
```
使用以下命令:
```bash
git ls-tree HEAD example
```
能得到类似如下结果:
```
160000 commit c2459db584158403a05821f8a56327b9936cdbe1 example
```
据此执行以下命令恢复目标submodule
```bash
git update-index --add --cacheinfo 160000,c2459db584158403a05821f8a56327b9936cdbe1,example
git submodule sync --recursive
git submodule update --init --recursive example
```
这种恢复方法相较于重新执行git submodule add命令不会出现新的submodule commit ID。