Tola Odejayi Tola Odejayi - 1 month ago 16
Git Question

Using git clean to delete an untracked directory but not delete a subdirectory in that directory

I have the following:

C:\src\MyUntrackedDir
C:\src\MyUntrackedDir\SubDirToBeDeleted1
C:\src\MyUntrackedDir\SubDirToBeDeleted2
C:\src\MyUntrackedDir\SubDirToBePreserved


I want to be able to delete
C:\src\MyUntrackedDir\SubDirToBeDeleted1
and
C:\src\MyUntrackedDir\SubDirToBeDeleted2
, but I do not want
C:\src\MyUntrackedDir\SubDirToBePreserved
to be deleted.

I thought that this should work:

git clean -f -d -x -e C:\src\MyUntrackedDir\SubDirToBePreserved


But that just ends up deleting everything in
C:\src\MyUntrackedDir
, including
C:\src\MyUntrackedDir\SubDirToBePreserved
.

How can I fix this?

Answer

First and foremost, the rules can be tricky. It's crucial to not run git clean -f ... blindly. Replace -f with -n first, and observe what would happen. If the output looks good, only then replace the -n with -f.


If a parent directory is selected for removal (MyUntrackedDir in your example), you cannot exclude items inside, they will all be removed. You could have preserved SubDirToBePreserved this way, for example:

C:
cd src
git clean -f -d -x -e MyUntrackedDir\SubDirToBePreserved MyUntrackedDir

This way, MyUntrackedDir itself is not selected for removal, only its contents, except the excluded MyUntrackedDir\SubDirToBePreserved.

Another alternative that would also work:

C:
cd src\MyUntrackedDir
git clean -f -d -x -e SubDirToBePreserved
Comments