Search code examples
gitgitignore

Ignore everything in a specific directory but exclude some files in the ignored directory


In my git repo, I have several directories. I'm ignoring One among many directories completely. But I want to exclude (whitelist) a single file which is nested in that directory. Something like this

!*/Databases/
!Databases/Links_Databases.txt
!Databases/AFLW/README.txt

Here the second line works, but the third line doesn't work. Nested README.txt file is still ignored. How can I whitelist that file?

I found few answers here: One, two and three. But the solutions provided here ignores everything in the root directory. I'll have to manually whitelist other directories I want to include. So, it didn't serve my purpose.

Preferably, I would like to edit my main gitignore file only. If there is no other way, I'm okay with creating another gitignore in a subdirectory.


Solution

  • You have to 'unignore' the directory under which the file resides:

    # Ignore all contents of Databases directory
    Databases/*
    # Except this direct child file
    !Databases/Links_Databases.txt
    # And the relevant subdir
    !Databases/AFLW/
    # Ignore all contents in subdir
    Databases/AFLW/*
    # Except this file we want to keep
    !Databases/AFLW/README.txt
    

    Although it's not strictly a duplicate, there is a very similar question with good explanations in the answers here: .gitignore exclude folder but include specific subfolder