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

  1. Open the .gitmodules file in the root directory of your project.
    • This file contains a list of all submodules in your repository.
  2. 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>
    
  3. Save the .gitmodules file.

Step 2: Unstage the Submodule

  1. Use the following command to remove the submodule from Git’s index:
    1git rm --cached My-SubModule
    

Step 3: Remove the Submodule Files

  1. Delete the submodule directory from your working directory:
    1rm -rf My-SubModule
    

Step 4: Clean Up Repository Configuration

  1. Open the .git/config file (local Git configuration).
  2. 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

  1. Commit the removal of the submodule:
    1git commit -m "Removed submodule My-SubModule"
    
  2. Push the changes to the remote repository:
    1git push origin <branch_name>
    

Translations: