How to Remove a Submodule in Git: Step-by-Step Guide
To remove a submodule in Git, first delete its entry from the
.gitmodules file and the Git configuration, then remove the submodule directory and stage the changes. Finally, commit the removal to update the repository.Syntax
Removing a submodule involves these main steps:
git submodule deinit -f <path>: Unregister the submodule.- Remove the submodule entry from
.gitmodulesand.git/config. - Delete the submodule directory with
rm -rf <path>. - Stage the changes with
git add .gitmodules <path>. - Commit the changes with
git commit -m "Remove submodule".
bash
git submodule deinit -f <path>
git rm -f <path>
rm -rf .git/modules/<path>
rm -rf <path>
git commit -m "Remove submodule"Example
This example shows how to remove a submodule located in libs/mylib:
bash
git submodule deinit -f libs/mylib
git rm -f libs/mylib
rm -rf .git/modules/libs/mylib
rm -rf libs/mylib
git commit -m "Remove submodule libs/mylib"Output
[removed] libs/mylib
rm: remove directory 'libs/mylib'? y
[master abc1234] Remove submodule libs/mylib
2 files changed, 1 deletion(-)
delete mode 160000 libs/mylib
Common Pitfalls
Common mistakes when removing submodules include:
- Not running
git submodule deinitfirst, which can leave stale config entries. - Forgetting to remove the submodule directory manually, leaving files behind.
- Not committing the changes to
.gitmodulesand the repository, causing confusion for collaborators.
Always follow all steps to fully clean the submodule.
bash
git rm libs/mylib rm -rf libs/mylib # This misses deinit and cleaning .git/modules, causing issues # Correct way: git submodule deinit -f libs/mylib git rm -f libs/mylib rm -rf .git/modules/libs/mylib rm -rf libs/mylib
Quick Reference
Summary of commands to remove a Git submodule:
| Command | Purpose |
|---|---|
| git submodule deinit -f | Unregister submodule from Git config |
| git rm -f | Remove submodule from index and working tree |
| rm -rf .git/modules/ | Delete submodule's Git data |
| rm -rf | Remove submodule files from disk |
| git commit -m "Remove submodule" | Commit the removal changes |
Key Takeaways
Always run 'git submodule deinit -f ' before removing a submodule.
Remove the submodule directory and its Git metadata to fully clean it.
Commit changes to '.gitmodules' and the repository to finalize removal.
Skipping steps can leave broken references and cause confusion.
Use 'git rm -f ' to remove the submodule from Git tracking.