Apr 5, 2023 6 min read

Gitignore: How to Ignore Files and Directories in Git

Ignore Files and Directories in Git with our tutorial. The .gitignore file tells Git which untracked files to ignore.

Ignore Files and Directories in Git
Table of Contents

Introduction

Before we begin talking about how to ignore files and directories in Git – What is Gitignore?

Gitignore is a powerful feature in Git that allows developers to exclude specific files or directories from being tracked in a repository. By creating a .gitignore file, developers can tell Git which files to ignore, preventing them from being committed or staged.

This is especially useful for excluding sensitive data, temporary files, or build artifacts that shouldn't be shared or stored in a repository. Understanding and utilizing Gitignore helps streamline version control and keeps repositories clean and efficient. Learn more about Gitignore and how to use it effectively for better code management.

In this tutorial, you will learn to ignore files and directories in Git.

Advantages of Gitignore

  1. Streamlines Version Control: Gitignore allows developers to exclude unnecessary files, making version control more efficient.
  2. Protects Sensitive Data: Gitignore helps keep sensitive information, such as passwords or API keys, from being accidentally committed to a repository.
  3. Prevents Build Artifacts: By ignoring build outputs, Gitignore keeps repositories clean and avoids bloating the repository with unnecessary files.
  4. Enhances Collaboration: Gitignore ensures that only essential files are shared, improving collaboration by eliminating clutter and confusion.
  5. Simplifies Deployment: Ignoring deployment-specific files allows for easier and cleaner deployments, saving time and reducing errors.

What Files Should be Ignored?

Ignored files are typically platform-specific files or ones generated automatically by build systems.

  • Runtime files, such as log, lock, cache, or temporary files, are frequent examples.
  • Files that contain sensitive data, such as passwords or API keys.
  • Dependency folders, such as /vendor or /node_modules.
  • Compiled code, such as .class or .o.
  • Create directories like /public, /out, and /dist.
  • IDE or text editor configuration files.
  • System files such as .DS_Store or Thumbs.db.

.gitignore Patterns


Each line of the .gitignore file contains a pattern for which files or folders should be ignored.

It matches filenames with wildcard characters using globbing patterns. If you have files or folders that include a wildcard pattern, you can escape the character with a single backslash (\).

Comments

Comments are lines that begin with a hash mark (#) and are disregarded. Empty lines can be used to improve the file's readability and to group relevant pattern lines.

Slash

A directory separator is represented by the slash symbol (/). The slash at the start of a pattern refers to the directory where the .gitignore file is located.

If the pattern begins with a slash, it only matches files and directories in the repository's root directory.

The pattern matches files and folders in any directory or subdirectory if it does not begin with a slash.

When a pattern ends in a slash, it only matches directories. All files and subdirectories in a directory are disregarded when it is ignored.

Literal File Names

A literal file name with no special characters is the most straightforward pattern.

Pattern Example Matches
/access.log access.log
access.log access.log, logs/access.log , var/logs/access.log
build/ build

Wildcard Symbols

* - The asterisk symbol is used to indicate that zero or more characters match.

Pattern Example Matches
*.log error.log, logs/debug.log , build/logs/error.log

** - Any file or zero or more directories are represented by two adjacent asterisk symbols. It only matches directories when preceded by a slash (/).

Pattern Example Matches
logs/** Matches anything inside the logs directory
**/build var/build, pub/build , build
foo/**/bar foo/bar , foo/a/bar , foo/a/b/c/bar

? - The question mark matches any single character.

Pattern Example Matches
access?.log access0.log , access1.log , accessA.log
foo? fooab, foo23 , foo0s

Square Brackets

[...] - Any of the characters enclosed in square brackets will be matched. A range of characters is denoted when two characters are separated by a hyphen -. All characters between those two characters are included in the range. The ranges might be numeric or alphabetical.

The pattern matches any character except those from the specified set if the first character after the [ is an exclamation mark (!).

Pattern Example Matches
*.[oa] file.o , file.a
*.[!oa] file.s, file.1 , file.0
access.[0-2].log access.0.log, access.1.log , access.2.log
file.[a-c].out file.a.out, file.b.out , file.c.out
file.[a-cx-z].out file.a.out,file.b.out , file.c.out , file.x.out, file.y.out , file.z.out
access.[!0-2].log access.3.log, access.4.log , access.Q.log

Negating Patterns

Any file that was ignored by the previous pattern is negated (re-included) by a pattern that starts with an exclamation point (!) The only exception is the re-inclusion of a file if its parent directory is excluded.

Pattern Example Matches
*.log,!error.log error.log or logs/error.log will not be ignored
foo? fooab, foo23 , foo0s

.gitignore Example

Here's an example of how your .gitignore file might look:

# Ignore the node_modules directory
node_modules/

# Ignore Logs
logs
*.log

# Ignore the build directory
/dist

# The file containing environment variables 
.env

# Ignore IDE specific files
.idea/
.vscode/
*.sw*

Local .gitignore

In most cases, a local .gitignore file is stored in the repository's root directory. You can, however, create multiple .gitignore files in your repository's subdirectories. The patterns in the .gitignore files are matched relative to the file's location in the directory.

Lower-level directories (sub-directories) files specify patterns that take precedence over those in higher-level directories.

Local .gitignore files are shared across developers and should include patterns that are relevant to all other users of the repository.

Personal Ignore Rules

The .git/info/exclude file should be used to establish patterns that are specific to your local repository and should not be shared with other repositories.

This file can be used to ignore created files from your personal project tools, for example.

Global .gitignore

You may also use Git to build a global .gitignore file in which you can establish ignore rules for all Git repositories on your system.

You can name the file whatever you like and save it anywhere you want. The home directory is the most typical location for this file. You'll need to create the file manually and configure Git to use it.

To make /.gitignore_global the global gitignore file, for instance, do the following:

1) Make the file as follows:

touch ~/.gitignore_global

2) Add the following file to Git's configuration:

git config --global core.excludesfile ~/.gitignore_global

3) Use your text editor to open the file and add your rules.

Global rules are very handy for disregarding specific files that you never want to commit, such as sensitive data files or compiled executables.

Ignoring Previously Committed Files

Your working copy's files can either be tracked or untracked.

To ignore a previously committed file, first unstage it and remove it from the index, then add the following rule to your .gitignorefile:

git rm --cached filename

The --cached option instructs git to remove the file from the index rather than the working tree.

Use the -r option to remove a directory in a recursive manner:

git rm --cached filename

Omit the --cached option if you wish to remove the file from both the index and the local disc.

When deleting files recursively, use the -n option to make a "dry run" to see what files will be deleted:

git rm -r -n directory

Debugging .gitignore File

It can be difficult to figure out why a file is being ignored, especially if you're working with multiple .gitignore files or intricate patterns. The git check-ignore tool with the -v option, which allows git to display details about the matching pattern, is useful in this situation.

To see why the www/yarn.lock file is disregarded, for example, run:

git check-ignore -v www/yarn.lock

The path to the gitignore file, the number of the matching line, and the actual pattern are all displayed in the output.

Output

www/.gitignore:31:/yarn.lock	www/yarn.lock

The command supports multiple filenames as arguments, and the file does not need to be in your working tree.

Display All Ignored Files

The --ignored option to the git status command provides a list of all ignored files:

git status --ignored

FAQs About Gitignore

What can I include in a Gitignore file?

You can specify file patterns, directories, or even specific files to ignore using wildcards and regular expressions.

How do I ignore a specific file in Git?

Add the file's name or pattern to your Gitignore file, and Git will disregard any changes or commits related to that file.

Can I ignore multiple files with similar names using Gitignore?

Yes, you can use wildcards like asterisks (*) or question marks (?) to match multiple files with similar names.

Can I ignore files already tracked by Git?

Yes, but you need to remove them from the repository first using the git rm --cached command before adding them to the Gitignore file.

Can I create multiple Gitignore files in a repository?

Yes, you can have multiple Gitignore files in different directories to define rules specific to those directories.

How do I check if my Gitignore rules are working?

Use the git status --ignored command to see which files are ignored based on your Gitignore rules.

Can I override Gitignore rules for specific files?

Yes, you can use the git add --force command to include ignored files, but be cautious as it may lead to unintentional commits of sensitive data.

Conclusion

You can use the .gitignore file to prevent files from being checked into the repository. The file contains globbing patterns that tell you which files and directories to ignore.

gitignore.io is an online tool for creating .gitignore files for your operating system, programming language, or IDE.

If you have any queries, please leave a comment below and we’ll be happy to respond to them.

Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to DevOps Tutorials - VegaStack.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.