Git – How to remove folder recursively from Git

From time to time, I accidentally start versioning some folders or files which should be not part of the repository. However, the commit is made, and the content is pushed to Git repository.

This article contains several clever commands for removal of unwanted files in your git repository.

Beginner mistake is often to use git rm DIRECTORY for directory removal. However, this Git command removes not only a directory from the repository, but also physically removes it from the local file system.

Fixing commit or patchset is necessary. However, we need to use --cached  flag in the Git command. This correct command formulation removes the content from the Git index.

Adding -r flag we create a Git command which recursively removes the content of the directory (including the directory folder itself) from the Git repository without directory and its content being physically removed from the local file system:

git rm --cached -r DIRECTORY

For the single file removal:

git rm --cached -r FILE.TXT

Quick hack: You can also remove files from the repository based on your .gitignore without deleting them from the local file system :

git rm --cached `git ls-files -i -X .gitignore`

Alternatively on Windows Powershell:

git rm --cached $(git ls-files -i -X .gitignore)

So if you have some folders or files which do not belong to the repository, now can make fixing commit or patchset with file/folder removal.

This entry was posted in Tips & tricks and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.