How to use .gitignore to include files in nested subdirectories

Background

Typically .gitignore is used to ignore files – but what do you do when you want to include files?

The trick when including files is to make sure that you include the whole tree that you are traversing. Every single subdirectory must be included before the file you want to include. Also make sure you start with * on an empty line and that everything you want to include (also the directories) start with an !

How to Use .gitignore to include files

In the example below we want to include accounts_import.csv, transactions_import.csv, and statement-1234.csv

Note who two sections are defined, the whole tree down to seeds and the whole tree down to statements

Normal git ignores
...
*
!storage/
!storage/app/
!storage/app/database/
!storage/app/database/seeds/
!storage/app/database/seeds/accounts_import.csv
!storage/app/database/seeds/transactions_import.csv
!storage/app/database/seeds/root_cards.csv

!storage/app/public/
!storage/app/public/statements/
!storage/app/public/statements/statement-1234.csv

To check if it is working properly, use the command below:

git check-ignore -v -- /path/to/a/file/to/add

Reference

https://stackoverflow.com/questions/53551601/i-edited-gitignore-to-allow-my-images-storage-folder-to-upload-but-when-i-push

Share this article

Share on facebook
Share on twitter
Share on linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top