How to Add an Empty Directory to a Git Repository

  1. First Solution
  2. Second Solution
  3. Shared .gitignore files in the 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 into the tmp folder for instructing Git to ignore everything in the folder.

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 it contains in your local copy.

For adding the empty directory to the Git Repository you need to add .gitignore to every empty folder with the following content:

*
!.gitignore

The .gitignore file tells Git to add this file on the repository and add the folder ignoring all other files of that folder. The .gitignore 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 .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.


Do you find this helpful?

Related articles