Last updated

Removing untracked files and directories with git

I just tried writing some new code, but it was no success. This happens, but it left me with a working copy littered with new and changed files.

# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#	modified:   config/routes.rb
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   db/migrate/20111231131752_create_validations.rb
#	vendor/assets/images/
#	vendor/assets/javascripts/
#	vendor/assets/stylesheets/custom.sass

So, how do I get rid of this mess?

1 - Be absolutely sure you want to delete your work

I sometimes commit my work although it’s of no use to me at the moment. It’s in a separate branch anyway and can be easily ignored until I come back to it.

So, if you’re really sure you want to delete your changes and files, continue to step 2.

2 - Delete untracked files and directories

Now, delete all files that are not yet tracked by git. You could do it like this:

rm -r db/migrate/20111231131752_create_validations.rb vendor/assets/images \
vendor/assets/javascripts/ vendor/assets/stylesheets/custom.sass

This requires you to copy/paste or type all the files and directories you want to delete. There’s a much easier way: ask git to do it for you:

git clean -df

The d option tells git to include directories, f says that you really want to perform the delete. Optionally, you can first run with n instead of f to see what’s going to happen - a so called dry-run.

If you use this command frequently and don’t want to specify the f options every time you can set clean.requireForce in your ~/.gitconfig to true to omit the f options.

3 - Reset changes to tracked files

With all the new stuff out of the way, let’s clean up the files that are tracked by git. You want to revert everything back to the last commit you made:

git reset HEAD --hard

That’s all. You’re now back to a clean working directory at HEAD. Start over now.

Tags: git