Git子模块克隆错误:拉取含子模块仓库后初始化失败
解决Git子模块克隆失败的问题
问题根源
你在local-repo1中添加project2子模块时,使用了./project2这个本地相对路径作为URL。当父仓库推送到remote-repo后,local-repo2拉取代码时,Git会将该URL解析为../remote-repo/project2——但remote-repo是裸仓库,并不存在project2这个独立子仓库,因此克隆失败。
修复步骤
方法1:修正父仓库的子模块URL并重新推送(推荐)
- 先为project2在remote-repo中创建独立的裸仓库:
cd /home/user/Sandbox/remote-repo git init --bare project2.git - 进入local-repo1/project2目录,将代码推送到新创建的remote仓库:
cd /home/user/Sandbox/local-repo1/project2 git remote add origin /home/user/Sandbox/remote-repo/project2.git git push -u origin master - 回到local-repo1根目录,修改
.gitmodules文件中的project2 URL,指向remote-repo中的project2裸仓库:[submodule "project2"] path = project2 url = /home/user/Sandbox/remote-repo/project2.git branch = master - 提交并推送父仓库的修改:
git add .gitmodules git commit -m "fix submodule project2 url to remote repo" git push origin master - 回到local-repo2,拉取最新代码并初始化子模块:
cd /home/user/Sandbox/local-repo2 git pull git submodule update --init
方法2:直接在local-repo2中临时修正子模块URL
如果不需要修改远程父仓库,可直接在local-repo2中调整:
- 编辑local-repo2中的
.gitmodules文件,将project2的URL改为local-repo1/project2的绝对路径:[submodule "project2"] path = project2 url = /home/user/Sandbox/local-repo1/project2 branch = master - 同步子模块配置并初始化:
git submodule sync git submodule update --init
后续注意事项
- 添加子模块时,禁止使用本地相对路径作为URL,除非所有克隆该父仓库的环境都有完全一致的本地目录结构。
- 子模块的URL必须是所有克隆者都能访问的地址:本地实验用绝对路径,线上环境用Git服务器的HTTPS/SSH地址。
内容的提问来源于stack exchange,提问作者samax
相关产品推荐
相关产品推荐

