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

There is a popular solution to this problem. It is just simply adding an empty .gitkeep file to every empty folder. After adding you can stage and commit the file and add the folder to version control.

mkdir -p some/path
touch some/path/.gitkeep
git add some/path/.gitkeep
git commit

The .keep is not a feature of Git but just a popular convention. The only purpose of this file is making the directory visible to Git.

After adding other files to the folder, you can safely delete it.

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).

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