Bootstrap FreeKB - Git (Version Control) - Remove untracked files using the git clean command
Git (Version Control) - Remove untracked files using the git clean command

Updated:   |  Git (Version Control) articles

The most basic way to use Git is to use the git clone command to clone an origin Git repository (such as example.git) to a directory on your PC (such as /home/john.doe/git), make a change to a file in the cloned repository on your PC (such as example.txt), use the git commit command to commit the change to the file, and to then use the git push command to upload the file to the origin Git repository.

 

Branches are used as an isolated way to make changes to files in a repository. A common example would be to create a new branch using the git branch or git checkout command, switch to the new branch using the git checkout command, make a change to a file, commit the change using the git commit command, and then merge the branch to the master branch using the git merge command.

 

Let's say you create a new file in the directory of the cloned repository.

touch foo.txt

 

The git status command will now show that foo.txt is an untracked file

~]# git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       foo.txt

 

Typically, the git add command would be used to add the file to the currently selected branch of the cloned repository. However, let's say you no longer need the file. The git clean command can be used to remove untracked files. By default, the git clean command should return something like this, because there is no way to undo the removal of untracked files, hence this warning is displayed to prevent untracked files from being mistakenly removed.

~]$ git clean
fatal: clean.requireForce defaults to true and neither -n nor -f given; refusing to clean

 

The git clean -n command can be used to show which untracked files would have been removed, but will not actually remove any files.

~]$ git clean -n
Would remove foo.txt

 

The git clean command with the -f or --force option can be used to remove untracked files. This will also delete the actual file, similar to the Linux rm (remove) command.

~]$ git clean --force
Removing foo.txt

 

Optionally, a specific file can be removed by including the path to the file.

~]$ git clean --force my-files/bar.txt
Removing my-files/bar.txt

 

Or, all of the untracked files in a specific directory can be removed.

~]$ git clean --force -d my-files
Removing my-files/foo.txt
Removing my-files/bar.txt

 

After the git clean --force command has been run, the git status command should show that there are no untracked files.

~]# git status
# On branch master
nothing to commit, working directory clean

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 076401 in the box below so that we can be sure you are a human.