Make .Gitignore Ignore Everything except a Few Files
Better Stack Team
Updated on June 24, 2024
To make .gitignore
ignore everything except a few files, you can use a combination of negation patterns and explicit file entries. Here's how you can achieve that:
- Open or create a
.gitignore
file in the root directory of your Git repository. Add the following patterns to ignore everything except the files you want to include:
# Ignore everything * # Except the following files !file1.txt !file2.txt
Replace
file1.txt
andfile2.txt
with the names of the files you want to include. You can add more!filename
lines for each additional file you want to include.Save the
.gitignore
file.
This configuration will cause Git to ignore all files in the repository except for the explicitly listed files (file1.txt
, file2.txt
, etc.).
Note:
- The `` pattern matches all files in the repository and tells Git to ignore them.
- The
!
prefix negates the pattern and tells Git to include files that match the following pattern. - Be careful when using negation patterns in combination with `` as it can have unintended consequences if not used correctly.
- Make sure to list all files that you want to include explicitly. Git will only include files that match the explicitly listed patterns.
Got an article suggestion?
Let us know