Ton Snoei

Remove a submodule from Git the right way

Published 1 year ago2 min read
Git

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:
    [submodule "My-SubModule"]
        path = My-SubModule
        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:
    git rm --cached My-SubModule
    

Step 3: Remove the Submodule Files

  1. Delete the submodule directory from your working directory:
    rm -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:
    git commit -m "Removed submodule My-SubModule"
    
  2. Push the changes to the remote repository:
    git push origin <branch_name>