Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

The great thing about Git is that almost all actions are reversible! But there's one command that isn't, and it can cause real headaches — git clean.

# remove all untracked files
git clean .

The clean command removes untracked files from your Git working tree, and while that's sometimes exactly what you want, you should really run the command with caution.

You're probably frustrated when you want to start over, but you should be sure you want to throw away everything. Some files might still be valuable. If you run git clean, they're gone — end of story.

By default, Git will not allow you to clean up a repository unless you have clean.requireForce set to false. But you know how it is: an innocent -f is quickly added.

I learned today that git clean (and other commands) support a --dry-run option.

git clean --dry-run .
Would remove not-important.js
Would remove untracked-but-very-important.js

If you want a shorter command line option, use the very intuitive (not!) -n argument.

git clean -n .
Would remove not-important.js
Would remove untracked-but-very-important.js

The command prints out what it would remove without doing any damage. Handy! It also comes with a useful interactive mode to handle many untracked files.

git clean -i
Would remove the following items:
  not-important.js   untracked-but-very-important.js
  
*** Commands ***
  1: clean   2: filter by pattern   3: select by numbers   4: ask each   5: quit   6: help
What now> 4
Remove not-important.js [y/N]? y
Remove untracked-but-very-important.js [y/N]? N
Removing not-important.js

You can choose between pattern matching or checking each file one by one in the interactive mode. Nice one, Git! 💪

But what about other Git commands? Most of the other dry runs don't seem very exciting to me because, as said, most of the Git operations are reversible. But one that I could see come in handy is a git remote prune dry run to avoid removing remote branches. But that's about it. 🤷‍♂️

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles