首页 > 解决方案 > 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?

标签: gitgitignore

解决方案


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不要从工作树中删除文件,而只是停止跟踪它们。


推荐阅读