How to add empty folder/directory in Git


In this article, we will see how we can add an empty folder in git that can be tracked by Github.

The current design of git is such that it only tracks files in your repository and any folder/ directory which is empty is ignored by git. Git cannot add a completely empty folder.

If you have an empty folder it will be shown in your local repository but when you push your folder to git, it will be ignored.

But any directory or folder that has files in them will be automatically added to your remote git repository.

So how can we add an empty folder to a git repository?

Since there is no official way provided by git, we can use some hacks to track empty folders in our git repository using:

  1. The .gitignore file
  2. The .gitkeep file, or
  3. The readme.md file

Let's see how we can use these files to add an empty directory in our git repos.

Using .gitignore to add empty folder in Git

The .gitignore file comprises a list of files and folders that we want git to ignore from tracking in our repository.

However, we can also use this .gitignore file to add an empty folder.

You can add an empty directory to git by just creating an empty .gitignore file inside the folder.

For example, let's say you have a folder named "extras" which is empty in your repo

/myproject/content/extras

and you want to add it to the git repository when you commit and push, then add the .gitignore file (with no content) inside it like this.

/myproject/content/extras/.gitignore

Now, git will track this folder and its future files whenever you make any changes to it.

Using .gitkeep to track empty folder/directory in Git

Since a .gitignore file have a specific purpose in git, therefore it becomes confusing to see a .gitignore file in an empty folder.

To avoid this confusion, people started using the .keep or .gitkeep convention.

Note: .gitkeep is not an official feature of git. You cannot find any documents related to it on the git official site.

The .gitkeep or .keep is just like a placeholder, a dummy file that is used as a convention to track an empty folder in the git repository.

So if you want to add or track empty folders/directories in your repo then just add the .keep or .gitkeep file (with no content) in the folder like this

/myrepo/content/empty-folder/.gitkeep

Now git will consider the folder with a file and start tracking it.

Using the README.md file in your repo to add an empty folder

You can also add a README.md file inside your empty folder to be tracked by git.

Open the empty folder in your repository and create a file named README.md and then commit and push the repo on git.

Since git tracks all folders with a file in them, the empty folder(with README.md file) will also be added to the repo.

Conclusion: It's better to use the .gitkeep file inside an empty folder than using .gitignore to avoid confusion among people who might clone or fork your repository.


💾 Recommended Articles