How to Add an Empty Directory to a Git Repository

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 tmp. You should add the .gitignore file to the index before you instruct Git to ignore it (and everything else in the empty directory):

mkdir tmp

touch tmp/.gitignore

git add tmp

echo '*' > tmp/.gitignore

git commit -m 'Empty directory' tmp

Second Solution

There are cases when the empty directories should always remain empty on Git no matter what the local copy they contain.

To add the empty directory to the Git Repository by adding .gitignore to every empty folder which contains the following:

git does not allow empty directories.
Yet, we need to add this empty directory on git.
To achieve that, we created this .gitignore file, so that the directory will not be empty thus enabling us to commit it.
Since we want all generated files/folders in this directory to be ignored by git, we add a rule for this.
*
And then add an exception for this specific file (so that we can commit it).
!.gitignore

The .gitignore file tells Git to add this file on the repository and add the folder ignoring all other files.The .gitignore file can be updated to allow additional files to be added to the repository whenever you need them.

Shared .gitignore files in the repository

The .gitignore 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 .gitignore file at the root of the repository.

The checked in .gitignore file in your repository is versioned like other files and is shared with your team when you git push. Only include patterns in .gitignore to benefit other users of the repository.


Do you find this helpful?

Related articles