Does Git delete empty folders

gitgithub

I deleted all files from a directory in my work folder, but the directory itself still exists. After pushing the changes to a remote repository (GitHub) I checked my project and noticed that the directory was gone. Is it possible that Git deletes empty folders?

Best Answer

Why is the directory not shown?

Git does not track directories; it only tracks files.

If there are no files in a directory, that directory does not “exist” to Git when adding or removing files. Particularly, a directory will disappear from Git's index when you've deleted all files from it and add that change to the index. Vice-versa, a directory will not be added via git add if it's empty.

In other words: If you can see the directory locally in your file browser, but it disappeared from GitHub, you most likely removed all files from the directory, added that change to the index, and committed and pushed it.

How do I track an empty directory, then?

If you want to explicitly track an empty directory, you have to create a file in it. Since Git won't track empty directories, you have to trick it into doing so by adding a file in the directory to Git's index.

Usually, people store a file called .gitkeep in a directory that they wish to track, but where the directory should stay empty for the time being. You can give the file any other name, of course, but the name .gitkeep is a convention. The .gitkeep file (due to starting with a .) will not be shown by file listings on most systems.

Instead of .gitkeep, some users also like to put a README file there instead, ideally with a short description of why the directory has to exist in the first place.

Example

$ mkdir foo
$ git init
$ git add .
$ git ls-files   # which files does Git know about?
                 # apparently, none
$ touch foo/bar  # create a file in the directory
$ git add .
$ git ls-files   # does Git know about it now?
foo/bar          # yep!

Here, the foo directory only gets added to the index once a file is in it.

What if I really want to track an empty directory?

That all said, in principle, the underlying data structure allows Git to store an empty directory, since it would be represented by an empty “tree”. Some further reading here and here.

Related Question