Ignoring Files with .gitignore
Scope
This document introduces the .gitignore
file and how it can be used to ignore and exclude files from being tracked in a Git repository.
Introduction to Ignoring Files with .gitignore
At some point during your daily activities, you will come across files in your local repository that you may not want Git to track. These files are usually anything from developer-specific configurations containing passwords/secret keys, large data sets, or other files not well-suited for tracking in version control. This is where .gitignore
comes in.
When identifying which files to track, Git leverages a file, .gitignore
, that can live anywhere in your repository. By default, .gitignore
files cascade, and you can have additional .gitignore
files in subfolders that have different "instructions". Pattern matching can also be utilized to ignore certain types of files.
Example: Typically Ignored RStudio Project Files
For example, a typical project done in RStudio will have the following .gitignore
file:
.Rproj.user/
.Rhistory
.RData
.Ruserdata
This specifies to ignore the folder .Rproj.user, and files .Rhistory, .RData, and .Ruserdata.
These files are used internally by RStudio to track the project sessions and do not make sense to check in.
Example: Ignoring Specific Files
For files you may generate, for an example where you do not want to track a file my_secrets.R
, as well as any PDF outputs into a reports folder, the following .gitignore
file could be created.
my_secrets.R
reports/*.pdf
A concept that sometimes gives people some difficulty is the concept that Git only really cares about files, not folders, hence if you have an empty folder, Git never really acknowledges that and will not track it, so if pushed to another person, that folder would not exist.
This can be problematic if scripts or other programs expect that folder to already exist, and thus an empty .gitignore
file can be used as a placeholder.
Example: Ignoring All Files within a Folder
One other trick that .gitignore
files can be used for, is when you have an output folder that you want to persist, but to not track any content inside. To ignore all files/folders within that folder, the .gitignore
file would look like:
*
!.gitingore
This signifies: "Ignore everything in this folder, but !(not) the .gitignore itself".
NOTE: Files already staged/tracked by Git will not be affected by .gitignore
. See the "Removing Unintentionally Added Files" of our Git Mistakes and FAQs page, if you have files that you have already checked in that you would like to remove and ignore going forward.