.gitignore exclude folder but include specific subfolder

 

To exclude a folder but include a specific subfolder within it in your .gitignore file, you can use negative patterns. Negative patterns allow you to override the exclusion of a parent folder for a specific subfolder. Here's how to do it with an example:

Suppose you have a directory structure like this:

markdown
my_project/ ├── excluded_folder/ │ ├── subfolder_to_include/ │ │ ├── file1.txt │ │ └── file2.txt │ └── other_files.txt └── other_files.txt

You want to exclude the excluded_folder but include subfolder_to_include and its contents.

Your .gitignore file should look like this:

gitignore
# Exclude the parent folder /excluded_folder/ # Include the specific subfolder and its contents !/excluded_folder/subfolder_to_include/

In this configuration:

  1. /excluded_folder/ is listed in the .gitignore file to exclude the parent folder.

  2. !/excluded_folder/subfolder_to_include/ is added after the exclusion rule to include the specific subfolder and its contents. The ! character negates the exclusion for this subfolder.

With these rules, Git will exclude the excluded_folder but include the subfolder_to_include and its contents when you commit and push changes.

Comments