.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.

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 us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build 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.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github