Garfield the Dummy
Garfield the Dummy

Reputation: 347

How to remove all untracked git files/folders except the ignored ones?

I do see some related questions but I haven't found the solution for my specific case. In my situation, I got some untracked files and folders (not git-ignored), and some other files and folders declared in .gitignore. I want to remove all the non-git-ignored, untracked files and folders, and keep all the git-ignored ones.

If I use git clean -f, the untracked files will be gone, while the folders remain. In case of running git clean -df, git-ignored folders will be deleted together with non-git-ignored ones.

What should I do?

Thanks in advance.

Upvotes: 0

Views: 245

Answers (1)

abligh
abligh

Reputation: 25119

I think you are confused about git clean's options.

  • git-clean -d cleans directories as well as files.
  • git-clean -x prevents git from processing .gitignore
  • git-clean -X only removes ignored files
  • git-clean -f is just a force option.

So the default behaviour of git clean -df is to remove files and folders except those which are ignored. That seems to be what you are asking for.

Demonstration:

amb@nimrod-ubuntu:~/so/git$ mkdir tmp
amb@nimrod-ubuntu:~/so/git$ cd tmp
amb@nimrod-ubuntu:~/so/git/tmp$ git init
Initialized empty Git repository in /home/amb/so/git/tmp/.git/
amb@nimrod-ubuntu:~/so/git/tmp$ echo "foo" > bar
amb@nimrod-ubuntu:~/so/git/tmp$ mkdir baz
amb@nimrod-ubuntu:~/so/git/tmp$ echo "baz" > baz/bob
amb@nimrod-ubuntu:~/so/git/tmp$ echo "bar" > .gitignore
amb@nimrod-ubuntu:~/so/git/tmp$ echo "baz" >> .gitignore
amb@nimrod-ubuntu:~/so/git/tmp$ echo ".gitignore" >> .gitignore
amb@nimrod-ubuntu:~/so/git/tmp$ ls -la
total 24
drwxrwxr-x 4 amb amb 4096 Dec  3 08:13 .
drwxrwxr-x 3 amb amb 4096 Dec  3 08:12 ..
-rw-rw-r-- 1 amb amb    4 Dec  3 08:13 bar
drwxrwxr-x 2 amb amb 4096 Dec  3 08:13 baz
drwxrwxr-x 7 amb amb 4096 Dec  3 08:12 .git
-rw-rw-r-- 1 amb amb   19 Dec  3 08:14 .gitignore
amb@nimrod-ubuntu:~/so/git/tmp$ ls -la baz
total 12
drwxrwxr-x 2 amb amb 4096 Dec  3 08:13 .
drwxrwxr-x 4 amb amb 4096 Dec  3 08:13 ..
-rw-rw-r-- 1 amb amb    4 Dec  3 08:13 bob
amb@nimrod-ubuntu:~/so/git/tmp$ git clean -df
amb@nimrod-ubuntu:~/so/git/tmp$ ls -la
total 24
drwxrwxr-x 4 amb amb 4096 Dec  3 08:13 .
drwxrwxr-x 3 amb amb 4096 Dec  3 08:12 ..
-rw-rw-r-- 1 amb amb    4 Dec  3 08:13 bar
drwxrwxr-x 2 amb amb 4096 Dec  3 08:13 baz
drwxrwxr-x 7 amb amb 4096 Dec  3 08:12 .git
-rw-rw-r-- 1 amb amb   19 Dec  3 08:14 .gitignore
amb@nimrod-ubuntu:~/so/git/tmp$ ls -la baz
total 12
drwxrwxr-x 2 amb amb 4096 Dec  3 08:13 .
drwxrwxr-x 4 amb amb 4096 Dec  3 08:13 ..
-rw-rw-r-- 1 amb amb    4 Dec  3 08:13 bob

Upvotes: 1

Related Questions