How to .gitignore a folder (exclude) but include specific subfolder?

Sometimes you want to add a folder to your .gitignore-file while keeping a sub-folder of said folder in version control. To ignore a folder but keep a specific subfolder in git, you can add a pair of rules to your .gitignore file to ignore the parent folder and then add an exception rule that includes the desired subfolder.

Assuming your folder structure is as follows:

my_folder/
├── subfolder1/
│ ├── file1.txt
│ └── file2.txt
├── subfolder2/
│ ├── file3.txt
│ └── file4.txt
└── file5.txt

To ignore my_folder but include subfolder1, you would add the following lines to your .gitignore file:

# Ignore my_folder
my_folder/

# Except for subfolder1
!my_folder/subfolder1/

This will ignore my_folder and all of its contents, except for subfolder1 and its contents, which will be included in git version control.

Please note that the order of these rules is important. The ignore rule for my_folder must come before the exception rule for subfolder1, or it will be ignored.

🙏🙏🙏

Since you've made it this far, sharing this article on your favorite social media network would be highly appreciated 💖! For feedback, please ping me on Twitter.

Published