Search code examples
gitgitignore

gitignore doesn't ignore files in subdirectories


I am new to git and try to understand gitignore. So far I have a directory I want to exclude called build, except files with the name BUILD.

build/**
!build/**/BUILD

But it seems the BUILD file is excluded as well. Does anyone know what I am doing wrong?

resource/obj1/BUILD
resource/obj2/BUILD
resource/obj3/BUILD

Solution

  • You need to exclude (whitelist) folders firsts, then BUILD/ content:

    build/**
    !build/**/
    !build/**/BUILD/**
    

    See ".gitignore exclude folder but include specific subfolder"

    • build/** ignores files and folders, so build/aFolder/ is ignored
    • !build/**/BUILD/** attempts to whilelist a file under build/aFolder/BUILD/

    But: "It is not possible to re-include a file if a parent directory of that file is excluded."

    And: build/aFolder/ is an already ignored folder.

    Hence: !build/**/BUILD/** does not apply.

    Unless: you un-ignore folders first: !build/**/ (the trailing / is important):
    build/aFolder/ is no longer ignored, even though build/aFolder/<files> are still ignored by build/**.

    Then: the !build/**/BUILD/** can apply to the folder BUILD/ content (its files), because the folders !build/aFolder/ and !build/aFolder/BUILD/ are not ignored.


    Check if this is working then with:

    git check-ignore -v -- build/aFile
    git check-ignore -v -- build/path/to/BUILD/aFile
    

    The first command should return a .gitignore rule line.
    The second command should not return anything, since the file should not be ignored.