Git Submodule 使用指南

July 15, 2026 · Misc #git

how to use git submodule

git的子模块使用,似乎值得说一说 不少使用了git很久的人,对这一块也不算太熟,实际上子模块的使用是个重要的技能

add git submodule

通过在 git submodule add 命令后面加上想要跟踪的项目的相对或绝对 URL 来添加新的子模块 比如git submodule add https://github.com/chaconinc/MyConnector, 将会出现文件 .gitmodules git diff --submodule可以对比子模块的改动 注意 增加的子目录MyConnector 记录的 160000 模式。 这是 Git 中的一种特殊模式, 它本质上意味着你是将一次提交记作一项目录记录的,而非将它记录成一个子目录或者一个文件。

init git submodule

MyConnector 目录,是空的。 你必须运行两个命令:git submodule init 用来初始化本地配置文件, 而 git submodule update 则从该项目中抓取所有数据并检出父项目中列出的合适的提交。 git clone 命令传递 --recurse-submodules 选项,它就会自动初始化并更新仓库中的每一个子模块, 包括可能存在的嵌套子模块。

  • git clone --recurse-submodules =git submodule init + update
  • git submodule update --init = git submodule init + update
  • git submodule update --init --recursive(嵌套)

由于网速和墙的原因,有些时候运行之后只有一个.git目录, 这时候不用急,直接跑到submodule里面git pull之后git reset —hard HEAD

operate git submodule

如果你不想在子目录中手动抓取与合并,那么还有种更容易的方式。 运行 git submodule update --remote,Git 将会进入子模块然后抓取并更新。 获取子模块更新 git fetch + git merge = git pull

how to update a existing submodule

  1. vim the .gitmodules to update to the new url
  2. git submodule sync
  3. git submodule update --init --recursive --remote
  4. git add and push to remote

some useful commands

git push --recurse-submodules=on-demand 根据需要同时推送子模块的改动

git submodule update --remote --merge

git submodule foreach 'git stash'

参考 GitScmBook