How to Add an Empty Directory in Git
When working with Git, there might be cases where you need to include an empty directory in your project. However, Git doesn’t track empty directories by default. In this article, we’ll show you how to add an empty directory in Git and make it trackable.
Method 1: Using .gitkeep
One common approach is to create a file named .gitkeep
in the empty directory. It doesn’t matter what content the file has, but Git will recognize the directory as a non-empty one.
Here’s an example of how to create an empty directory and add .gitkeep
file to it:
mkdir my-empty-directory
touch my-empty-directory/.gitkeep
The .gitkeep
file indicates that the directory should be kept even though it’s empty. This file also serves as a placeholder to prevent the directory from being ignored during the Git push.
Method 2: Using .gitignore
Another method is to use a .gitignore
file to specify that an empty directory should be tracked. With this method, you don’t need to add a .gitkeep
file. Instead, you can add the empty directory’s name to the .gitignore
file, and Git will automatically track it.
Here’s how to add an empty directory using the .gitignore
approach:
mkdir my-empty-directory
echo '!my-empty-directory/' > .gitignore
The !
sign in the .gitignore
file indicates that Git should track the directory. Since there are no other files in the directory, it’ll remain empty.
Method 3: Using an Existing File
If you already have a file in the directory that you want to track, then you can use this file to add an empty directory. This method is useful when you need to create directories for storing files that will be added to the repository later.
Here’s how to create an empty directory with an existing file:
mkdir my-empty-directory
touch my-empty-directory/.gitignore
By adding the .gitignore
file to the directory, Git will start tracking the directory. Later, you can add other files to the directory.
Method 4: Using Git-Add and the –force Option
Git provides a --force
option to add empty directories to the repository. You can use this option along with the git add
command to add the directory to the repository.
Here’s how to add an empty directory using this approach:
mkdir my-empty-directory
git add my-empty-directory --force
The --force
option will bypass the default behavior of Git to ignore empty directories while adding files to the staging area.
Conclusion
Adding an empty directory to Git is easy once you know the methods. You can choose what approach to take depending on your specific requirements. Whether you want to use an existing file, create a .gitkeep
file or a .gitignore
file, or use the --force
option in Git, you now have easy-to-follow steps to get you going. Happy tracking!