乐闻世界logo
搜索文章和话题

How do i add an empty directory to a git repository

3个答案

1
2
3

In Git, empty directories themselves are not tracked by version control because Git tracks changes to files, not directories. However, a common practice is to add a .gitignore file to the empty directory you want to track.

Here are the steps to add an empty directory to a Git repository:

  1. Create the empty directory you want to track on your local file system. For example, to track a directory named empty-folder:
bash
mkdir empty-folder
  1. Create a .gitignore file in this empty directory. This file can contain rules to tell Git which files to ignore, but in this case, it's used solely to keep the directory in place. Open a text editor, create a file named .gitignore, and add the following content:
shell
# Ignore everything in this directory * # Except this file !.gitignore
  1. This tells Git to ignore all files in the directory (* represents all files) but not the .gitignore file itself (!.gitignore).

  2. Add the newly created .gitignore file to version control:

bash
git add empty-folder/.gitignore
  1. Commit the changes to your Git repository:
bash
git commit -m "Add empty-folder with .gitignore"
  1. Push the changes to the remote repository (if applicable):
bash
git push

Using this method, although the directory is empty, the .gitignore file ensures that Git includes the directory in version control. This is a common approach for handling empty directories in Git.

2024年6月29日 12:07 回复

.gitkeep creates an empty file named .gitkeep in the directory, then git add . adds it. By default, this will be a hidden file on Unix-like systems, but it forces Git to recognize the directory's existence because it now has content. Also note that the file name has no special significance; you can name it anything you want. Git only cares that the directory contains content.

2024年6月29日 12:07 回复

touch .placeholder

On Linux, this creates an empty file named .placeholder. Regarding its purpose, the name is irrelevant to Git, and this approach is commonly used in other system locations, such as /etc/cron.d/.placeholder.

Secondly, as another user pointed out, .git can be used to reserve prefix conventions for files and directories that Git itself employs for configuration purposes.

Alternatively, as another answer states, the directory can contain a descriptive README.md file.

Regardless of the method, it requires that the presence of the file does not cause your application to crash.

2024年6月29日 12:07 回复

你的答案