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:

  1. Open or create a .gitignore file in the root directory of your Git repository.
  2. 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 and file2.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.

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