git - How to stop tracking the content of a directory in git?
问题描述
I have a directory named img
. I want to that directory be exits on the repo, but always it should be empty. I mean just the content of that directory should be untracked.
Here is a simplified of my project:
myproject/
.git/
application/
public/
img/
img1.jpg
img2.jpg
vendor/
composer.json
composer.lock
I want to make it like this on repository:
myproject/
.git/
application/
public/
img/
vendor/
composer.json
composer.lock
How can I do that?
According to some researches, I have to use .gitignore
file. But how? Should I make a .gitignore
file on the root of project and write this in it?
// .gitignore file
public/img/*
Or should I make a .gitignore
inside img
directory? If yes should I write what thing in it?
Ok, now I got a new problem. Let's explain what I want to do exactly. Here is the scenario:
I develop my website locally and push it on the github repository. Then I go in the server and do a git pull
. Also there is an img
directory that contains all user's avatars. All I'm trying to do is to keep the real-users avatar on img
directory. If I put the whole img
directory inside .gitignore
, then avatars won't be created (because of lack of img
directory). If I exclude the content of img
directory, then all current user's avatars will be gone when I do a new git pull. Any idea how can I handle such a situation?
解决方案
Git 不跟踪目录,只跟踪文件。
为了在 repo 中添加一个空目录,您必须在其中放置一个文件并在项目的.gitignore
.
但是,因为 Git 存储库允许.gitignore
在每个目录中放置一个文件,所以您可以在要排除的目录中放置一个文件,并将这些行放入其中:
# Ignore everything in this directory
*
# ... but do not ignore this file
!.gitignore
将新文件添加到存储库并提交。
就这样。
如果您想将所有忽略规则保存在一个位置(在.gitignore
项目根目录中的文件中),那么您可以在目录中放置一个空文件以忽略并将上述规则以路径为前缀放入.gitignore
文件中。
通常,这样一个空文件被命名.gitkeep
(名字无所谓,这个是用来表达它的目的的)。在这种情况下,添加到.gitignore
项目的文件中:
/public/img/*
!/public/img/.gitkeep
如果您已经将文件添加public/img
到存储库(并提交了它们),则必须先删除它们才能不再被跟踪。跑
git rm --cached public/img/*
并将此更改与.gitignore
. 该--cached
参数告诉git rm
不要从工作树中删除文件,而只是停止跟踪它们。
推荐阅读
- php - 保存会话数据并将其发布到数据库
- css - 仅将类应用于具有该类的元素而不是所有子元素
- sql - 我们可以在 SQL 中的 SELECT 中使用 CASE 子查询来选择表中的列吗?
- sql - 如何在有条件的 T-SQL 中显示 SUM() 值?
- asp.net-mvc - Kendo MVC:网格列中的下拉菜单
- javascript - 如何将动态项目从数组打印到 DOM
- mysql - 如何从关系表中获取数据(多对多)
- angular - 如何侦听 MSAL-Angular 令牌重新身份验证请求?
- python - 如何从 Python 客户端设置与 NodeJS websocket 的 SocketIO 连接?
- python - PyQt5 和 Anaconda:ModuleNotFoundError:没有名为“PyQt5”的模块