特性分支引入子模块变更时,如何正确切换分支?
Git子模块分支切换问题解答
场景说明
- master分支子模块配置:
[submodule "content-repo"] path = content-repo url = https://github.com/dogweather/forkful.git [submodule "themes/ananke"] path = themes/ananke url = https://github.com/theNewDynamic/gohugo-theme-ananke.git - 特性分支hextra-yet-again子模块配置:
[submodule "content-repo"] path = content-repo url = https://github.com/dogweather/forkful.git [submodule "themes/hextra"] path = themes/hextra url = https://github.com/imfing/hextra.git - 切换回master时的警告:
出现两个遗留问题:$ git checkout master warning: unable to rmdir 'themes/hextra': Directory not empty M content-repo Switched to branch 'master' Your branch is up to date with 'origin/master'.- content-repo子模块停留在特性分支的新提交,未恢复到master分支的对应状态
- themes/hextra子模块目录及文件未被移除
操作正确性判断
你的分支切换流程本身没问题,出现这些问题是Git子模块的默认行为导致的:Git切换分支时不会自动重置子模块的提交状态,也不会主动清理不属于当前分支的子模块目录,并非操作错误,只是需要额外步骤完成完整的分支切换。
解决步骤
1. 重置content-repo子模块到master分支指定提交
切换到master后,执行以下命令同步子模块到当前分支的期望版本:
git submodule update --init --recursive
该命令会读取master分支的子模块配置及对应提交记录,将content-repo拉取并切换到master分支指定的提交版本。
2. 清理themes/hextra残留目录
themes/hextra在master分支中不属于追踪的子模块,属于未追踪的残留目录,需手动删除:
rm -rf themes/hextra
若担心误删,可先备份目录再执行删除操作。
分支切换前的优化操作
下次切换分支前,先在特性分支执行以下命令取消子模块注册,能减少切换后的遗留问题:
git submodule deinit -f .
完成后再切换到master分支,最后执行git submodule update --init --recursive初始化master分支的子模块即可。
内容的提问来源于stack exchange,提问作者Dogweather
相关产品推荐
相关产品推荐

