git clean: Remove untracked files from the working tree

The git clean command in Git is used to remove untracked files from the working tree. Untracked files are files that are not being tracked by Git, meaning they are not part of any commit history.

Here’s an elaboration on its usage and functionality:

When you run git clean, it scans the working tree and identifies files that are not tracked by Git. These untracked files can be generated as a result of compiling code, running tests, or creating temporary files during development. The git clean command allows you to safely remove these untracked files from your working directory.

Here are a few key points to understand about git clean:

  • Removing Untracked Files: By default, git clean only operates on untracked files, ensuring that you don’t accidentally delete files that are part of the Git repository or have local modifications. It will remove files that are not tracked by Git, including untracked directories and subdirectories.
  • Dry Run: Before actually removing any files, you can perform a dry run using the -n or –dry-run option. This will show you a list of files that would be removed without actually deleting them. It allows you to preview the impact of the clean operation.
  • Force Removal: To actually remove the untracked files, you need to use the -f or –force option. This ensures that the clean operation proceeds forcefully without any further confirmation prompts. Exercise caution when using the force option to avoid unintended data loss.
  • Ignoring Files: git clean respects the rules specified in the .gitignore file. By default, it will not remove files and directories that are ignored by Git. However, you can use the -x or –force option to include ignored files in the clean operation.

It’s important to note that git clean permanently deletes untracked files, and the operation cannot be undone. Therefore, it is recommended to review the list of files to be removed carefully and ensure that you have a backup or a way to recover any important files before executing the clean command.

The git clean command is useful when you want to tidy up your working directory by removing untracked files that are cluttering your project. It helps keep your repository clean and organized by removing temporary or generated files that are not intended to be part of the version control.

git clean Command Examples

1. Delete files that are not tracked by Git:

# git clean

2. Interactively delete files that are not tracked by Git:

# git clean -i

3. Show what files would be deleted without actually deleting them:

# git clean --dry-run

4. Forcefully delete files that are not tracked by Git:

# git clean -f

5. Forcefully delete directories that are not tracked by Git:

# git clean -fd

6. Delete untracked files, including ignored files in .gitignore and .git/info/exclude:

# git clean -x
Related Post