Git – Remove untracked files matching a pattern

Reading Time: 2 minutes

Solution

$ git clean [-n] -f <path>...

Example

Run:

$ git clean -n -f *.json

to remove all untracked json files.

Important note

Always use -n or --dry-run before running the command.

Explanation

  • git clean – Remove untracked files from the working tree.
  • -n or --dry-run – Show the list of files that would be removed without actually removing.
  • -f or --force – If the Git configuration variable clean.requireForce is not set to false, git clean will refuse to delete files or directories unless given -f or -i. Git will refuse to modify untracked nested git repositories (directories with a .git subdirectory) unless a second -f is given.

Other options:

  • -d – Normally, when no <path> is specified, git clean will not recurse into untracked directories to avoid removing too much. Specify -d to have it recurse into such directories as well. If any paths are specified, -d is irrelevant; all untracked files matching the specified paths (with exceptions for nested git directories mentioned under --force) will be removed.
  • -i or --interactive – Show what would be done and clean files interactively.
  • -e or --exclude – Use the given exclude pattern in addition to the standard ignore rules.

We transform challenges into digital experiences

Get in touch to let us know what you’re looking for. Our policy includes 14 days risk-free!

Free project consultation