Remove directories from Git tracking

0
4530
Remove directories from Git tracking

While developing, you somehow made a mistake that added wrong directories into Git, and you want to remove directories from Git tracking without deleting directories on disk. This is what you’re gonna do.

Remove directories from Git tracking

I often make this mistake, especially when creating a new Git project. Let say, I’m creating a new project using IntelliJ IDEA. Then, automatically through my natural behaviors, I will issue these commands.

$ git init
$ git add .
$ git commit -m "Init project"
$ git push origin master

Verify the tracking list again:

$ git ls-files
.idea/
README.md

Eh oh, .idea/ should not stay in Git tracking list.

That’s why I often need to do a very funny task, that is, remove directories from Git tracking, and it should not actually remove them from storage, I mean disk.

To do it, this is what I do.

$ git rm -r --cached .idea/
rm '.idea/learn-python.iml'
rm '.idea/misc.xml'
rm '.idea/modules.xml'
rm '.idea/workspace.xml'

The above command will remove all files, including .idea/ directory from Git cache. Next, is to add this directory to ignore list and verify git status.

$ touch .gitignore
$ echo ".idea/" >> .gitignore
$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        deleted:    .idea/learn-python.iml
        deleted:    .idea/misc.xml
        deleted:    .idea/modules.xml
        deleted:    .idea/workspace.xml

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        .gitignore

So far so good, the final step is to commit all of that into Git.

$ git commit -m "Remove .idea/ directory, add to ignore list"
[master a6ee2f9] Remove .idea/ directory, add to ignore list
 5 files changed, 1 insertion(+), 178 deletions(-)
 create mode 100644 .gitignore
 delete mode 100644 .idea/learn-python.iml
 delete mode 100644 .idea/misc.xml
 delete mode 100644 .idea/modules.xml
 delete mode 100644 .idea/workspace.xml

Summary

That’s how I remove directories from Git tracking list.

In Git, everything is possible, it is just too many commands and options to learn. Hope this tip can help someone troubling with same problem I have.