Bash script to automatically convert git submodules to regular files

August 3, 2016

Git submodules drive me batty! They are a great idea in theory however in practical application they are a pain in the butt to work with.

I have a project that has accumulated over a dozen submodules over the past couple years. Switching branches and merging anything has become excruciating. This morning was the last straw. I WANT THEM GONE! Removing dozens of submodules by hand is time consuming so I tossed together this quick Bash script. I hope it is helpful to anyone else out there struggling with git submodules.

#!/bin/bash

# Get a list of all the submodules
submodules=($(git config --file .gitmodules --get-regexp path | awk '{ print $2 }'))

# Loop over submodules and convert to regular files
for submodule in "${submodules[@]}"
do  
   echo "Removing $submodule"
   git rm --cached $submodule # Delete references to submodule HEAD
   rm -rf $submodule/.git* # Remove submodule .git references to prevent confusion from main repo
   git add $submodule # Add the left over files from the submodule to the main repo
   git commit -m "Converting submodule $submodule to regular files" # Commit the new regular files!
done

# Finally remove the submodule mapping
git rm .gitmodules