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
.gitignorefile 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.txtReplace
file1.txtandfile2.txtwith the names of the files you want to include. You can add more!filenamelines for each additional file you want to include.Save the
.gitignorefile.
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