W3docs

How to Add an Empty Directory to a Git Repository

The empty directories will not be added to version control by Git as it supports only files. In this snippet, find some fast solutions to this problem.

Git does not register empty directories. It supports only files. Thus, the empty folder won’t be added to version control by Git. In this tutorial, we are going to show some approaches to this problem.

First Solution

Let's assume you need an empty directory named <kbd class="highlighted">tmp</kbd>. You should add the .gitignore file into the <kbd class="highlighted">tmp</kbd> folder for instructing Git to ignore everything in the folder.

add empty folder to git

mkdir tmp
echo '*' > tmp/.gitignore
git add tmp
git commit -m 'Empty directory' tmp

Alternatively, you can use a .gitkeep file instead of .gitignore as the standard convention for empty directories.

Second Solution

There are cases when the empty directories should always remain empty in Git no matter what it contains in your local copy.

For adding the empty directory to the Git Repository you need to add <kbd class="highlighted">.gitignore</kbd> to every empty folder with the following content:

*
!.gitignore

The <kbd class="highlighted">.gitignore</kbd> file tells Git to add this file to the repository and add the folder ignoring all other files of that folder. The <kbd class="highlighted">.gitignore</kbd> file can be updated to allow additional files to be added to the folder whenever you need them.

Shared .gitignore files in the repository

The <kbd class="highlighted">.gitignore</kbd> files can be defined in different directories in the repository. Each pattern is tested relative to the directory containing that file. However, the simplest way is to define a single <kbd class="highlighted">.gitignore</kbd> file at the root of the repository.

The checked in <kbd class="highlighted">.gitignore</kbd> file in your repository is versioned like other files and is shared with your team when you git push.