Cleaning untracked files and directories in git
You can use “git clean” with different options to clean untracked files in a git branch.
In the below setup, we have two untracked files by the names untrackedfile1 and untrackedfile2. We also have one directory with the name untrackeddir1 with an untracked file untrackedfile3.
~/repoone$ git status
On branch main
Your branch is up to date with 'origin/main'.
Untracked files:
(use "git add <file>..." to include in what will be committed)
untrackeddir1/
untrackedfile1
untrackedfile2
nothing added to commit but untracked files present (use "git add" to track)
~/repoone$ ls untrackeddir1/
untrackedfile3
“git clean -n” and “git clean –dry-run” would show what all files would get cleaned, without actually running the actual command.
~/repoone$ git clean -n
Would remove untrackedfile1
Would remove untrackedfile2
~/repoone$ git clean --dry-run
Would remove untrackedfile1
Would remove untrackedfile2
“git clean -f <file name>” would clean only that specific file. Here we clean up untrackedfile1.
~/repoone$ git clean -f untrackedfile1
Removing untrackedfile1
~/repoone$ git status
On branch main
Your branch is up to date with 'origin/main'.
Untracked files:
(use "git add <file>..." to include in what will be committed)
untrackeddir1/
untrackedfile2
nothing added to commit but untracked files present (use "git add" to track)
“git clean -f” would clean only the files and not directories. You can see that untrackeddir1 and files under it did not delete here.
~/repoone$ git clean -f
Removing untrackedfile2
~/repoone$ git status
On branch main
Your branch is up to date with 'origin/main'.
Untracked files:
(use "git add <file>..." to include in what will be committed)
untrackeddir1/
nothing added to commit but untracked files present (use "git add" to track)
“git clean -fd” would delete all the untracked files as well as untracked directories.
~/repoone$ git clean -fd
Removing untrackeddir1/
~/repoone$ git status
On branch main
Your branch is up to date with 'origin/main'.
nothing to commit, working tree clean
You can also use “git clean -i” to interactively clean up files and directories, as shown.
~/repoone$ touch untrackedfile1
~/repoone$ git clean -i
Would remove the following item:
untrackedfile1
*** Commands ***
1: clean 2: filter by pattern 3: select by numbers 4: ask each 5: quit 6: help
What now> clean
Removing untrackedfile1