tekin.co.uk

Delete those pesky untracked files from your Git repository

We’ve all been there. In the process of writing some code you’ve ended up with a bunch of new files in your Git repository that you no longer need.

  $ git status
  On branch new-blog-post

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

    _posts/draft-2018-11-15-branch-in-time.md
    images/graphics.png
    images/logo.png
    output.log

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

Your working directory is now cluttered up with these untracked files, and they’re getting in the way. Whilst you could copy/paste the file paths to the rm command in your terminal, or even use your OS’ file manager to delete them, there is a way faster and less error-prone way: using Git’s very own clean command!

Git clean

According to the docs, git clean will “remove untracked files from the working tree”.

By default, git clean will recursively remove all the untracked files in the current directory, but you can optionally pass in a path if you want to be more specific:

  $ git clean some/directory

Doing a dry run

To be extra safe, you might want to perform a dry run using the -n option (aka --dry-run) to see exactly which files will be deleted:

  $ git clean -n
  Would remove _posts/draft-2018-11-15-branch-in-time.md
  Would remove images/graphics.png
  Would remove images/logo.png
  Would remove output.log

Interactive cleaning

There’s also an interactive mode, where you can interactively make a decision on each file using -i (aka --interactive):

  $ git clean -i
  Would remove the following items:
    _posts/draft-2018-11-15-branch-in-time.md
    images/graphics.png
    images/logo.png
    output.log
  *** Commands ***
      1: clean                2: filter by pattern
      3: select by numbers    4: ask each
      5: quit                 6: help
  What now>

Are you very sure?

Out of the box Git is configured to require you pass the -f option (aka --force) to let it know you’re absolutely sure you want to delete all the untracked files:

  $ git clean
  fatal: clean.requireForce defaults to true and
  neither -i, -n, nor -f given; refusing to clean

  $ git clean -f
  Removing _posts/draft-2018-11-15-branch-in-time.md
  Removing images/graphics.png
  Removing images/logo.png
  Removing output.log

WARNING: There is no way to recover these files!

Because these files have never been tracked by Git, once they’re gone, they’re gone! So be extra sure you want those files gone before you run git clean in your repository.

So there you have it. Next time you need to get rid of untracked files in your repository, reach for git clean.

Want more juicy Git tips like this straight to your inbox?

You'll get an email whenever I have a fresh insight or tip to share. Zero spam, and you can unsubscribe whenever you like with a single click.

More articles on Git

Authored by Published by