How to Add an Empty Directory to a Git Repository

Learn three useful methods to add an empty directory inside of a git repository.

How to Add an Empty Directory to a Git Repository

Keeping your Git repository well organized is essential to having a healthy codebase. One caveat of git is that empty folders will not be committed by default. However, there are occasions when it’s beneficial to have an empty folder inside your repository. For example, your code may write files to this folder at some point, and it’s helpful if it already exists without having the code create the folder. Whatever your reasons, here is how to add an empty folder to a git repository.

How to Add an Empty Directory to a Git Repository

To add an empty directory into a Git repository, add either a .gitignore, .gitkeep, or README file inside the folder. Each solution achieves the goal of adding a file into the folder structure, forcing git to commit the folder to the repository. We will review the pros and cons of each solution below.

Option 1: Add .gitignore (preferred)

Our preferred solution is to add a .gitignore with the following content.

# Ignore all files and subdirectories in this folder
# Except the .gitignore file

This file will force git to ignore all of the contents of this folder except for the .gitignore file itself. This approach is beneficial if your development environment adds files you don’t want to be committed to your folder.

Option 2: Add .gitkeep

You can create an empty .gitkeep file inside your folder to signify that this folder should remain in the repository. Git does not officially support this file syntax, so it shouldn’t be confused with a proper git file. When committing your project, git will see this hidden .gitkeep file and commit it along with the folder.

Option 3: Add a README

Another approach is to add a README file inside the folder explaining why this empty directory needs to be maintained inside the repository. This approach is helpful if you are working on a team or will be handing the project off to someone else. You may want to add a README along with a .gitignore file to get a more complete and thorough solution.

Now you have multiple solutions for how to add an empty directory to a git repository. Choose what works best for your use case but consider using options one and three together for a robust and well-documented answer. 

We hope you found this guide helpful. For more guides like this, please check out our Coding Section.