How to Ignore Everything Except Some Files in Git

John Wachira Feb 02, 2024
How to Ignore Everything Except Some Files in Git

This article outlines the steps to make Git ignore all files except a few in a Git repository. The .gitignore file is a useful Git utility that allows us to tell Git what files to track and the files not to track.

If you want the .gitignore file to ignore everything except a few files, stick around, we have a lot to unpack.

Ignore Everything Except Some Files in Git

Take this hypothetical situation.

We have a dozen added files in our repository and only want to share work on files, namely, run.py, index.html, and package.json.

One way of doing this is by adding these files to the index using the git add command. Another way of doing this involves the .gitignore file.

How do we tell gitignore to ignore everything except the three files?

If the files are in the root directory, we can edit our .gitignore file, as shown below.

# Ignore everything
/*
# Except these files
!.gitignore
!run.py
!index.html
!package.json

This will make Git ignore everything except the mentioned files. What if our files are in a subdirectory?

Let’s assume our files are all in one directory called apps, and there are other files in the same directory. Here is what our .gitignore file would look like.

# Ignore everything
/*
# do not ignore the .gitignore file
!.gitignore
#do not ignore the apps directory
!/apps
# ignore everything in the apps directory
/apps/*
# do not ignore these files in the apps directory
!/apps/run.py
!/apps/index.html
!/apps/package.json

In a nutshell, you can instruct Git to ignore everything except a few files by adding the ! in the .gitignore file, as illustrated in the examples above.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Ignore