git-clean - Linux


Overview

git-clean is a command used to remove untracked files and directories from a Git working tree. It helps maintain a clean working directory by removing files that are not under version control or are no longer needed.

Syntax

git clean [options] [<paths>...]

Options/Flags

  • -d, –dry-run: Simulate the cleaning process without actually deleting any files.
  • -f, –force: Force deletion of untracked files, bypassing interactive confirmation prompts.
  • -i, –interactive: Prompt for confirmation before deleting each untracked file.
  • -n, –dry-run: Synonym for --dry-run.
  • -x, –exclude: Exclude matching files and directories from being deleted. Can be used multiple times.
  • -q, –quiet: Suppress progress messages.
  • -a, –all: Also remove ignored files.
  • –exclude-from=: Read exclude patterns from the specified file.
  • –file-mode=: Exclude files that have a mode specified by <mode> (e.g., -rw-r--r-).

Examples

Remove all untracked files:

git clean -f

Remove specific untracked files:

git clean -f file1 file2

Exclude files matching a pattern:

git clean -x '*.tmp'

Remove also ignored files:

git clean -f -a

Common Issues

  • "fatal: untracked working tree files would be overwritten by merge": This error occurs when merging changes from another branch that introduced files that are already present in the working tree but not tracked by Git. To resolve this, stash the untracked changes or add them to the staging area before merging.
  • "cannot unlink":: This error indicates that the file or directory cannot be deleted. Check for file permissions or whether the file is in use by another process.
  • "skipping untracked directories": git-clean skips removing untracked directories by default. Use the -d or -f options to force directory deletion.

Integration

git-clean can be combined with other commands for advanced cleaning tasks:

  • git clean -f && git commit -am "Clean working tree": Combine cleaning and committing in one command.
  • git clean -d | grep -vE '^\S+ -> .+': Exclude merge conflicts from the dry run output.

Related Commands

  • git rm: Removes files from the staging area and deletes them from the working tree.
  • git add: Adds files to the staging area to be committed.
  • git status: Shows the status of the working tree, including untracked and ignored files.