Git – How to remove folder recursively from Git

This article contains several clever commands to remove unwanted files in your git repository.

Commiting wrong files to repository

Sometimes, I accidentally start versioning some files or folders that should not be part of the repository. After that, I do not notice the wrong files being versioned, the commit is made, and the content is pushed to the Git repository. I am sure this happens to everybody from time to time.

How to remove unwanted files and folders from a repository?

There is only one way, a new fixing commit or patchset is necessary.

Beginner mistake is often to use only 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.

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

Be aware that we must use the --cached flag in the Git command. This correct command formulation removes the content from the Git index.

Here is a command for removing everything from the Git repository within the specific directory:

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 that do not belong to the repository, you can now make a fixing commit or patchset with files or folder removal.

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

Leave a Reply

Your email address will not be published.

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