50

I'm using Git for version control. Now I want to delete on my local machine all files in the repository that are not tracked.

I can use

git status 

to list these files, but how can I delete all of them?

3
  • 1
    Cant you just check out all the files to a different place one your machine and then delete the old version? Commented Sep 14, 2011 at 13:59
  • 1
    For sure I can, but isn't there a simpler way? Commented Sep 14, 2011 at 14:01
  • See also: Stack Overflow: How do I discard unstaged changes in Git?. Commented Mar 9, 2021 at 22:19

4 Answers 4

68

If you have it in ignore, use git clean -xf. You can do git clean -df but that will also remove un-tracked directories. Use -n for a dry-run.

See cleaning up un-tracked

4
  • 3
    -x ignores the ignores.. Commented Apr 10, 2014 at 19:01
  • 10
    -xf will delete and the ignored files and this is probably NOT what you want. Use -nf and proceed with care. See: stackoverflow.com/questions/61212/… Commented Jul 9, 2014 at 21:13
  • 2
    Remember, this may remove your environment/IDE folders (e.g. .vagrant or .idea (phpstorm)) Commented Nov 21, 2014 at 12:12
  • 1
    WATCHOUT! gitignored files will be purged forever. -100 Commented Feb 26, 2019 at 14:45
9
 git clean -f 
1
  • 10
    It might make sense to add the meaning of that command to make this answer self-contained. Commented Sep 14, 2011 at 18:47
5

User interactive approach:

git clean -i -fd Remove .classpath [y/N]? N Remove .gitignore [y/N]? N Remove .project [y/N]? N Remove .settings/ [y/N]? N Remove src/com/amazon/arsdumpgenerator/inspector/ [y/N]? y Remove src/com/amazon/arsdumpgenerator/manifest/ [y/N]? y Remove src/com/amazon/arsdumpgenerator/s3/ [y/N]? y Remove tst/com/amazon/arsdumpgenerator/manifest/ [y/N]? y Remove tst/com/amazon/arsdumpgenerator/s3/ [y/N]? y 

-i for interactive
-f for file
-d for directory

Note: Add -n or --dry-run to just check what it will do.

3

There is a subtlety worth mentioning about git clean -f vis-a-vis untracked files and directories. If you have an untracked directory that contains files which are, a fortiori, untracked, then git clean -f will NOT delete those untracked files.

In other words, it is NOT always the case that git clean -f will delete all untracked files. A better explanation of git clean -f is that it deletes all untracked files that are not in untracked directories.

git clean -f -d must be used to delete untracked files that are in untracked directories and there appears to be no way to delete all untracked files without also deleting untracked directories that only contain untracked files.

Use git clean -f -d -n to REALLY see what you want to do to restore your working directory to what it would be without any untracked files. Then use git clean -f -d to do that.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.