Remove a submodule from Git the right way
Removing a Git submodule cannot be done with a single command. It involves several steps that need to be followed carefully. In this article, I’ll explain how to remove a submodule from a Git repository.
In the example, we’ll work with a submodule located in the directory My-SubModule
that we want to remove. The steps are as follows:
Step 1: Remove the Submodule Reference
- Open the
.gitmodules
file in the root directory of your project.- This file contains a list of all submodules in your repository.
- Find and delete the section related to
My-SubModule
. It will look something like this:1[submodule "My-SubModule"] 2 path = My-SubModule 3 url = <submodule_url>
- Save the
.gitmodules
file.
Step 2: Unstage the Submodule
- Use the following command to remove the submodule from Git’s index:
1git rm --cached My-SubModule
Step 3: Remove the Submodule Files
- Delete the submodule directory from your working directory:
1rm -rf My-SubModule
Step 4: Clean Up Repository Configuration
- Open the
.git/config
file (local Git configuration). - Locate and delete the
[submodule "My-SubModule"]
section if it exists.
Step 5: Remove Submodule Traces from History (Optional)
If you want to completely erase all traces of the submodule from your repository’s history (e.g., from previous commits), you’ll need to rewrite the Git history using an interactive rebase or a tool like filter-repo
. This step is optional and not always necessary unless you have specific reasons to clean up the history. Let me know if you need help with this!
Step 6: Commit and Push the Changes
- Commit the removal of the submodule:
1git commit -m "Removed submodule My-SubModule"
- Push the changes to the remote repository:
1git push origin <branch_name>