Delete accidentally added .idea folder from git repository

Upasana | March 21, 2019 | 1 min read | 592 views


Sometimes we unintentionally add folders/files to git repository without knowing the consequences. Fortunately it is possible to keep the local copy while removing the versioned copy of these files/folders from git using command line.

Adding .idea to .gitignore

First of all, we shall always create a .gitignore file for each project and check it in version control. This is a special file in git that tells what all files/folders to ignore. Please be noted that it won’t remove something that is already committed, but it will prevent you from making the same mistake again.

A typical .gitignore will have following for a java project
.idea
build/
output/
target/
.gradle
*.iml

Removing already added files/folders from repo

We want to remove the .idea folder from repository, but we do not want to remove it locally.

Summary of commands
git rm -r --cached .idea    (1)
echo '.idea' >> .gitignore
git add .gitignore
git commit -m 'added .idea to ignored entries'
git push
1 -r flag will recursively remove all files under .idea directory from repository

If it is just a single file, you can use the below command

Removing a single file from repository
git rm --cached logfile.log
git commit -m 'added .idea to ignored entries'
git push

Recommended books for interview preparation:

Find more on this topic: