clean untracked directories only

386 Views Asked by At

If I rename some directories, then commit and push to the origin, and later pull from another computer I will find both the old an new directories. In the old directories there will be some ignored files. How do I remove all such untracked directories, without touching any file (tracked or untracked) in any tracked directory.

(With "tracked directory" I mean a directory with at least one tracked file inside.)

3

There are 3 best solutions below

0
On

You may be after git clean -X.

From git-scm

-X

Remove only files ignored by Git. This may be useful to rebuild everything from scratch, but keep manually created files.

Here's an example with one tracked, one untracted and one ignored file.

$ ls
x.txt  y.txt  z.txt

$ cat .gitignore
y.txt

$ git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

        z.txt

nothing added to commit but untracked files present (use "git add" to track)

$ git clean -X --dry-run
Would remove y.txt

$ git clean -Xf
Removing y.txt

$ ls
x.txt  z.txt

$ git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

        z.txt

nothing added to commit but untracked files present (use "git add" to track)

0
On

Try this:

git clean -d -fx

-d: tell git clean that you also want to remove any untracked directories, by default it will ignore directories.
-f: force option initiates the actual deletion of untracked files from the current directory.
-x: tell git clean to also include any ignored files.

0
On
git clean -dX

The -d option causes git-clean to recurse into untracked directories.

The -X option causes git-clean to remove ignored files.

You can also specify a directory to clean:

git clean -dX myDirectory

You could first try a dry run by adding the -n option. A dry run does not actually remove anything, it just shows what would be done.

git clean -dXn