5

If I have a directory app in my repository with a single, untracked file in it and I execute git clean -f, I get the message: Not removing app/ and the untracked file is still there.

But if I have an additional, tracked file within the same directory and I execute the exact same command then the untracked file is removed successfully.

So my question is: Why is Git trying to delete the directory if it would be empty after cleaning it from untracked files?

Below is a script which reproduces the behavior. Thanks in advance.

#!/bin/bash

# Create new empty repo
mkdir myrepo && cd myrepo
git init

# Create app directory with main.c
mkdir app
touch app/main.c

# Try to delete main.c with git clean -> Not working
git clean -f

# Add helper.c to app directory and add to index
touch app/helper.c
git add app/helper.c

# Try to delete main.c with git clean -> Now it's working
git clean -f
DAXaholic
  • 33,312
  • 6
  • 76
  • 74

2 Answers2

6

You need to pass the -d option for git clean to remove untracked directories.

Hasturkun
  • 35,395
  • 6
  • 71
  • 104
  • Thanks for the reply. But it is not clear to me why Git wants to delete the whole directory if it would be empty after the command. – DAXaholic Sep 01 '13 at 16:43
  • 1
    Well, git doesn't want to delete the directory (otherwise it would have done so as in your second case, instead of complaining and continuing). Since `git-clean` by default ignores untracked directories (or rather, directories with no tracked files), it never enters them. – Hasturkun Sep 01 '13 at 16:52
  • Ok, now I got the idea. The "... it never enters them" was the key ;) Thanks! – DAXaholic Sep 01 '13 at 17:11
2

git does not keep track of directories - you can't commit an empty directory to git.

(try creating an empty directory, and adding it to git - you won't see any changes in git status)

Even if you add some files to an untracked directory, git won't show you all the files in git status - it will just show the directory

Check this question for more answers on why git doesn't version directories.

So as @Hasturkun pointed out in his answer, you need to pass -d to git clean to remove untracked directories

Community
  • 1
  • 1
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186