How to add an empty directory in git
Git does not track empty directories. It only tracks files. This means if a directory has no files in it, Git will simply ignore it; it won't appear in your repository after you push your changes. However, there are legitimate reasons why you might want to keep an empty directory in your repository, such as preparing a placeholder for future files or maintaining a desired project structure.
This guide provides a detailed walkthrough on how to effectively manage and commit an empty directory in Git.
Step 1: creating a .gitignore
file in the empty directory
The standard workaround to commit an empty directory in Git is to include a file inside it.
One way to do this is to add a .gitignore
file to ensure the directory gets tracked while remaining functionally empty of other files. In the case where you want this directory to stay empty long-term,you can configure the .gitignore file to prevent any files in the directory from ever being committed.
Create the empty directory
First, create the directory you want to add to Git:
mkdir empty-directory
Add a .gitignore
file
Navigate into the empty directory and create a .gitignore
file:
cd empty-directorytouch .gitignore
Edit the .gitignore
file to include the following content:
# Ignore every file in this folder*# Except this one!.gitignore
These lines tell Git to ignore all files in this directory except for the .gitignore
file itself. This setup allows the directory to be included in the repository without holding any other files.
In the case you want to use this directory as a placeholder for future files, you can instead just create an empty dot file in the directory instead.
To create an empty dot file, run:
touch .foo
The .
prefix will prevent the file from showing up using standard file browsing commands like ls
, preventing it from cluttering your workflow, while at the same time allowing you to commit the file, preserving the empty directory in Git.
Step 2: adding and committing the directory
With the .gitignore
file in place, you can now add and commit the directory:
git add empty-directorygit commit -m "Add empty directory with .gitignore"
This sequence stages the empty-directory
and its .gitignore
file, and then commits them to your repository. The directory is now tracked by Git despite being empty of any other files.
Step 3: Pushing changes to a remote repository
If you are working with a remote repository, push your changes to ensure the empty directory is present in the remote repository as well:
git push origin main
Replace main
with whatever branch you are pushing to if different.
If your project requires committing a more complex empty folder structure, you'll need to repeat the entire process for each subdirectory. Each subdirectory would need its own .gitignore
or .foo
file to be included in the repository.
For further reading on how Git structures its file storage, see the official documentation.