Git by Example: Clean Untracked Files
Learn how to remove untracked files from your working directory. This is useful for cleaning up build artifacts, temporary files, or accidental creations.
Code
# 1. Dry run: See what would be deleted
git clean -n
# Output:
# Would remove dist/
# Would remove temp.log
# 2. Force delete untracked files
git clean -f
# 3. Force delete untracked files AND directories
git clean -fd
# 4. Force delete ignored files as well (e.g., build artifacts)
git clean -fxExplanation
The git clean command is used to remove untracked files from your working directory. Untracked files are files that are in your project folder but have not been added to Git's version control (and are not ignored). These often include build artifacts, temporary log files, or experimental scripts that you want to discard.
Because this command permanently deletes files, Git requires you to be explicit. It will often refuse to run without the -f (force) flag. A highly recommended best practice is to always run git clean -n (dry run) first. This shows you a list of exactly what will be deleted without actually touching anything, preventing accidental data loss.
By default, git clean does not remove untracked directories to protect you. If you want to clean up entire folders (like a dist/ or build/ directory), you need to add the -d flag, usually combining them as git clean -fd.
- Removes untracked files permanently
- Always use
-n(dry run) first - Use
-fto force deletion - Use
-dto include directories

