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

What are the differences between gitignore and gitkeep

4个答案

1
2
3
4

The .gitignore file tells Git which files and directories to ignore. Typically, these files are build artifacts, temporary files, or other types of files not part of the repository. Git will ignore any directory or file that matches the patterns specified in the .gitignore file.

Examples:

text
# Ignore .DS_Store files .DS_Store # Ignore build artifacts build/ # Ignore log files *.log

Instead, the .gitkeep file is used in Git to maintain otherwise empty directories. By default, Git does not track empty folders, so if you want to keep a directory in the repository, you must add a .gitkeep file to it. The filename is more important than the actual content of the file.

.gitkeep file example:

text
# This file is used to keep the directory empty in Git

Overall, the .gitignore file tells Git which files and directories to ignore. To maintain an otherwise empty Git directory, use .gitkeep. They serve different purposes and are distinct from each other.

2024年6月29日 12:07 回复
  • .gitignore is a text file that lists files Git will ignore or not add/update to the repository.
  • .gitkeep is a hack to preserve empty directories in the repository because Git deletes or does not add empty directories to the repository (though it is not officially part of Git).
  • Just execute touch /path/to/emptydirectory/.gitkeep to add the file, and Git will now keep this directory in the repository.
2024年6月29日 12:07 回复

.gitkeep is simply a placeholder file. This ensures Git doesn't forget the directory because Git only tracks files.

If you want an empty directory and ensure it remains 'clean' for Git, create a .gitignore file in the directory with the following content:

shell
# .gitignore sample # Ignore all files in this directory... * # ... except for this file. !.gitignore

If you want only a specific type of file to be visible to Git, here's an example of a .gitignore file that filters out all files except .txt files:

shell
# .gitignore to keep only .txt files # Filter all files... * # ... except the .gitignore file... !.gitignore # ... and all text files. !*.txt
2024年6月29日 12:07 回复

.gitkeep is not tracked because it is not a feature of Git.

Git cannot add completely empty directories. Those who wish to track empty directories in Git have established a convention of placing a file named .gitkeep within these directories. The file can be named arbitrarily; Git does not assign any special meaning to this name.

There is a competing convention where .gitignore is used to add files to empty directories for tracking purposes, but some find this confusing because the goal is to preserve empty directories rather than ignore them; .gitignore is also used to list files that should be ignored by Git when searching for untracked files.

2024年6月29日 12:07 回复

你的答案