.Gitignore Exclude Folder but Include Specific Subfolder
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.
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github