.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:
main/*
: This tells Git to ignore all files and directories inside themain/
folder.!main/subfolder2/
: This tells Git not to ignore thesubfolder2
directory.!main/subfolder2/**
: This tells Git to include all files and subdirectories insidesubfolder2
.
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 withinsubfolder2
is also included.
This setup should achieve the desired outcome of excluding a folder but including a specific subfolder and its contents.