Ignoring files in Git

Amir Ebrahimi Fard
Data Management for Researchers
2 min readJul 26, 2021

--

*** This article is inspired by [1][2] ***

Photo by Ian Barsby on Unsplash

Sometimes, we don’t want Git to keep track of every file in a folder. Some files contain private information, some are too big, some are binary, and some are temporary files generated by our operating system or other programs. In this situation, we need to tell Git to ignore a specified file, group of files or folder that we do not want to be tracked. To do this, we need to create a file called .gitignore within the root directory of the repository and use it to list the names of all the files and/or sub-folders that we want Git to ignore. For example, the following figure shows the contents of a sample .gitignore file:

Lines 5 and 6 tell Git to ignore all files with the extensions .png and .jpg in the entire repository. Line 7 ignores a subfolder called db/. Line 8 tells Git to ignore all the files in all the /temp/ folders. Line 9 ignores a folder called #numbers (note: the hash character (#) is normally used for commenting code; however, if a folder or file name starts with this character, then we need to use a backslash in front of it). In the last line we define an exception to Git ignoring /temp/ folders using an exclamation mark. Everything after this character will be exempted and thus the sub-folder videos/temp/ and all its contents will be tracked by Git.

It is also worth noting that we can tell Git to ignore the contents of the .gitignore file without first needing to commit that file or even add it to the stage. But it’s generally useful for everyone who wants to work with the repository to know what is in the .gitignore file — so it is recommended to commit this file. However, it is possible to stop Git from tracking the .gitignore file itself by adding its own name within the contents of .gitignore (i.e., adding .gitignore as a separate line to the .gitignore file ). We could also add the contents of the .gitignore files into the .git\info\exclude file [3].

In Windows, if you try to create a .gitignore file you’ll get an error in response. To fix this issue, instead of creating a file with the name .gitignore, name it slightly differently as: .gitignore. (with an extra dot at the end).

--

--

Amir Ebrahimi Fard
Data Management for Researchers

Postdoc Researcher on AI Explainability - Interested in the intersection of data, algorithm, and society.