Last Updated: March 30, 2023
·
263.1K
· wojtha

Keep your git directory clean with `git clean` and `git trash`

Do you have your git directory full of untracked files and it start to bothers you when you are picking the changes for commit? Well I have two tips for you!

git clean

This is builtin command to cleanup the untracked files. Be careful with this one, it deletes files permanently!

Always add -n or --dry-run options to preview the damage you'll do! (source)

  • If you just clean untracked files, run git clean -f
  • If you want to also remove directories, run git clean -f -d
  • If you just want to remove ignored files, run git clean -f -X
  • If you want to remove ignored as well as non-ignored files, run git clean -f -x

Note, that there is -f / --force option in each example, this is because of default configuration of git: If the git configuration variable clean.requireForce is not set to false, git clean will refuse to run unless given -f or -n.

git trash

Soft alternative to git clean. Moves all unstaged files to the .trash directory for later review.

First to have this command work you need to add .trash directory to the local or global .gitignore. If you don't do that git trash will try to remove the .trash folder as well.

echo ".trash" >> .gitignore

Now add the trash git shortcut to your global aliases list:

git config --global alias.trash '!mkdir -p .trash && git ls-files --others --exclude-standard | xargs mv -f -t .trash'

And you're done. Now you can run git trash in your root of git repository and all unstaged files will be moved to the .trash subdirectory.

Related protips:

Remove all your local git branches but keep master

4 Responses
Add your response

Why not go further and use trash from trash-cli.

over 1 year ago ·

Thanks for a nicely-written tip. Even better: commit much more frequently.

over 1 year ago ·

Oh, thank you very much this will help me a lot.

over 1 year ago ·

Use this if you want to get rid of directories too!

git clean -f -x -d

Trash directories

git config --global alias.trash '!mkdir -p .trash && git ls-files --others --exclude-standard --directory | xargs --no-run-if-empty mv -v -f -t .trash'
over 1 year ago ·