Adding Empty Directories to a Git Repository

Justin French, October 2008

One of the biggest WTF moments when I started using Git for version control was that it refused to add (or even recognize) empty directories in the repository.

The GitFaq sums it up just fine:

Currently the design of the git index (staging area) only permits files to be listed, and nobody competent enough to make the change to allow empty directories has cared enough about this situation to remedy it.

The same FAQ also documents the “hack” that most people choose to work around this limitation:

If you really need a directory to exist in checkouts you should create a file in it. .gitignore works well for this purpose; you can leave it empty, or fill in the names of files you expect to show up in the directory.

Fine, but I get a little sick of adding a bunch of .gitignore files to the many nested empty folders in a Rails project, or having to add the dirs myself when cloning something.

So here it is, a Bash one-liner which recursively adds an empty .gitignore file to every empty directory in the current working directory (with the exception of directories beginning with a dot, like .git for example:

for i in $(find . -type d -regex ``./[^.].*'' -empty); do touch $i"/.gitignore"; done;<code>

Add it into ~/.bashrc as an alias and save yourself precious minutes in every new project!

I’ve added it as a gist on GitHub, so feel free to make improvements to it.