.Gitignore Exclude Folder but Include Specific Subfolder

Better Stack Team
Updated on August 12, 2024

To exclude an entire folder in a Git repository except for a specific subfolder, you can use the .gitignore file with a combination of exclude (*) and include (!) rules.

Suppose you have the following directory structure:

 
project/
├── main/
│   ├── subfolder1/
│   ├── subfolder2/
│   └── subfolder3/
└── .gitignore

If you want to ignore everything inside main/ except for subfolder2/, your .gitignore file should look like this:

 
# Ignore everything in 'main' folder
main/*

# Except for 'subfolder2'
!main/subfolder2/

# Additionally, if there are files inside 'subfolder2' that should be included, you need to unignore those as well
!main/subfolder2/**

Here is an explanation of each line:

  1. main/*: This tells Git to ignore all files and directories inside the main/ folder.
  2. !main/subfolder2/: This tells Git not to ignore the subfolder2 directory.
  3. !main/subfolder2/**: This tells Git to include all files and subdirectories inside subfolder2.

By following these rules, you ensure that everything inside the main/ directory is ignored except for the subfolder2 directory and its contents.

Additional Notes:

  • Make sure the order of rules is correct because .gitignore processes patterns from top to bottom.
  • If subfolder2 contains files and further subdirectories, the !main/subfolder2/** rule ensures that everything within subfolder2 is also included.

This setup should achieve the desired outcome of excluding a folder but including a specific subfolder and its contents.

Got an article suggestion? Let us know
Explore more
Git
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.