How do I add an empty directory to a Git repository?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Git does not track empty directories because Git tracks files rather than directories. However, there are some common workarounds to ensure that an empty directory is included in your Git repository.
1. Use a .gitkeep File
The most common practice is to add a hidden file, usually named .gitkeep, to the empty directory. This file has no special meaning to Git, but it allows the directory to be tracked because it is no longer empty.
Steps:
- Create the directory if it doesn't exist:
- Create a
.gitkeepfile in the empty directory:
- Add the directory and file to Git:
- Commit the change:
2. Use an Empty .gitignore File
Another approach is to add an empty .gitignore file inside the empty directory. This method might be useful if you want to include a directory but prevent any other files from being accidentally committed to it.
Steps:
- Create the directory if it doesn't exist:
- Create an empty
.gitignorefile in the empty directory:
- Add the directory and file to Git:
- Commit the change:
3. Comment in the .gitignore File
If you want to use a .gitignore file but ensure that it has content (because empty files might be removed by some editors), you can add a comment inside the .gitignore file:
Steps:
- Create the directory if it doesn't exist:
- Create a
.gitignorefile with a comment:
- Add the directory and file to Git:
- Commit the change:
Summary
- Use
.gitkeep: This is a conventional way to include an empty directory by placing a.gitkeepfile inside. - Use
.gitignore: If you prefer, you can place an empty.gitignorefile or one with a comment inside the directory.
These methods allow you to ensure that the directory is tracked by Git even if it contains no files.
Related reading
- How do I change the author and committer name/email for multiple commits?
- How do I clone a Git repository into a specific folder?
- How do I clone all remote branches?
- How do I discard unstaged changes in Git?
- How do I find and restore a deleted file in a Git repository?
- How do I get the current branch name in Git?
- How do I make git use the editor of my choice for editing commit messages?
- How do I modify a specific commit?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.