Tracking only a type of files in Git

Here we will show you how to track a type of files in a Git repository by writing a proper .gitignore file.

To check the result of .gitignore in the following part, we assume you have a newly initiated Git repository with below directory structure.

|-- a.conf
|-- b.h
|-- conf/
|   |-- conf.conf
|   `-- extra/
|       `-- extra.conf
`-- include/
    `-- include.h

Track only a type of files

If you want to ignore all the *.conf files under the whole repository mentioned above, the .gitignore will as below:

# goal: ignore everything except /conf/**/*.conf 

# ignore everything in the root
*.*

# exclude *.conf
!*.conf

Test the .gitignore with git status:

$ git status
On branch master

Initial commit

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        a.conf
        conf/

nothing added to commit but untracked files present (use "git add" to track)

As you see, it prompts only a.conf and conf folder are untracked, while the include folder is not mentioned for it does not contain any conf file but the conf folder does. This means only the files mentioned being untracked by git status are expected to be tracked according to the rules inside the .gitignore.

Track only a type of files under a folder

Again take the repository mentioned in the beginning for example, assuming you want to track only *.conf files under conf directory as well as its subdirectories. Write the .gitignore file like this:

# goal: ignore everything except /conf/**/*.conf 

# ignore everything in the root
/*

# exclude /conf/
!/conf/

# ignore all files in /conf and its subdirectories
/conf/**/*.*

# exclude *.conf in /conf and its subdirectories
!/conf/**/*.conf

Test the .gitignore:

$ git status
On branch master

Initial commit

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        conf/

nothing added to commit but untracked files present (use "git add" to track)

As what is expected, it only prompt the conf folder is untracked.

Listing untracked files in Git

List all the untracked files, including ignored files

git ls-files command is used to list files, add -o or --others to list only untracked files:

# List all the untracked files, including the ignored files
$ git ls-files --others

List untracked files, excluding ignored files

--exclude-standard option excludes files in .gitignore, .git/info/exclude or the user’s global exclusion file.

# List untracked files, excluding the ignored files.
$ git ls-files --others --exclude-standard