How to remove all untracked submodules from local working directory?

时间:2016-04-04 16:37:52

标签: linux git command-line git-submodules

On my project, there are two branches I'm working on (Develop and Release), each of which makes generous use of submodules. The Develop branch uses about twice as many submodules as Release, because it is where we test ideas.

When I switch branches from Develop to Release, the directories of Develop-specific submodules stay where they are, and so they become untracked. This makes things a bit confusing for me, because I do occasionally need to add or remove submodules from Release as well, and the git status message becomes a long list of untracked modules, some of which I want to use and some I don't.

What I would like to do is remove all untracked submodules from my project as soon as I switch from Develop to Release, so that I'm working with a "clean slate", (IE no untracked submodules sitting in my working directory).

I have found several solutions to removing individual submodules one at a time, such as here: How do I remove a submodule?

However solutions such as this assume that the git submodules are in use and being tracked (which they are not), and it is also a pain in the neck to remove them one at a time when I'm working with something like 15-20 submodules.

I have also tried piping linux commands like so:

git ls-files --others --exclude-standard | rm -rf

But the command does not appear to do anything. I have also tried using the same with git rm -rf, to no avail.

Does anyone know if there is an easy to remove all untracked git submodules from a working directory? Any advice anyone can share on this matter would be greatly appreciated. Thank you!

1 个答案:

答案 0 :(得分:1)

With some advice from helpful folks in the comments section, I determined that there is no obvious, non-tedious solution to this problem. Instead I created a bash script that does the job for me. Here it is, in case anyone else has the same issue:

#!/bin/bash

clear
git ls-files --others --directory --exclude-standard
echo
read -r -p "Are you sure you want to remove these untracked submodules? [y/N] " response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]
then
    git ls-files --others --directory --exclude-standard | while read line; do
    rm $line/.git &> /dev/null;
  done
  git clean -d  -f
fi

Easy steps for people not super comfortable with Bash scripts:

Step 1: Copy the above script into a file and name it 'cleanUSM'. Save the file to /usr/bin. If you are having trouble saving it or finding /usr/bin, just save it to your current directory, and then use 'sudo mv cleanUSM /usr/bin/cleanUSM' to get it where it needs to go.

Step 2: From within your root directory, run the command 'cleanUSM'

Thanks to everyone who contributed!