How to use a .gitignore file (2024)

A .gitignore file prevents certain files and directories from being tracked by Git. This file helps developers exclude temporary, auxiliary, or sensitive data from being included in the repository, thereby keeping the repository clean, lightweight, and secure.

How a .gitignore file works

At its core, the .gitignore file operates through pattern matching. When Git processes the working directory for changes, it cross-references the list of files and directories against patterns defined in .gitignore files. Here’s a deeper look at how it functions technically:

Pattern matching

  • Wildcard Support: .gitignore supports wildcards such as * for matching any sequence of characters, ? for a single character, and [...] for a set of characters. For instance, *.log ignores all files with the .log extension.

  • Directory ignoring: By appending a slash (/) to the end of a pattern, Git specifically treats it as a directory. Without the slash, the pattern can match both files and directories.

  • Negation: A pattern prefixed with ! negates a match, allowing files that would otherwise be ignored to be included. For example, !important.log would track a file named important.log even if .log files are ignored.

Hierarchical and global .gitignore files

  • Local .gitignore: Each repository can have its own .gitignore file at the root level or additional .gitignore files in subdirectories. The patterns in these files apply to the directory where the file is located and its subdirectories. To prevent unexpected behavior it’s recommended to have one .gitignore file per repository.

  • Global .gitignore: Users can also define a global .gitignore file for all their repositories on a particular system, configured via the git config command. This is particularly useful for ignoring system-specific files (e.g., .DS_Store on macOS) across all projects.

Under the hood

When Git prepares to create a new commit, it looks at the working directory and stages changes. Here's what happens under the hood regarding .gitignore:

  1. Scanning: Git scans the working directory for changes. This includes new files, modified files, and deleted files compared to the last commit.

  2. Filtering: Before staging changes, Git filters the list of changed files through the .gitignore patterns. If a file matches a pattern, Git ignores it, meaning it won't stage, commit, or even display the file as untracked. This filtering happens every time Git scans for changes, ensuring that ignored files remain out of the version control system.

  3. Priority and order: Git applies .gitignore rules from the top of a file to the bottom. Patterns defined in a .gitignore file in a subdirectory take precedence over patterns in a higher directory or the root. Likewise, the global .gitignore provides a base set of ignore rules that can be overridden by local .gitignore files.

Efficiency

Internally, Git optimizes the handling of ignored files and directories for efficiency. When a directory is ignored, Git completely skips scanning it for changes, which can significantly speed up Git's operations in projects with large numbers of ignored files (e.g., node modules, and build artifacts).

The .gitignore file functions as a filter for Git's tracking system, using pattern matching to exclude specified files and directories from version control. This system allows developers to maintain clean repositories by excluding non-essential or sensitive data from being tracked and shared.

Utilizing a .gitignore file ensures your repository remains clean and only relevant files are tracked. Here are some best practices:

1. Commit .gitignore early

Commit a .gitignore file as early as possible in your project's lifecycle—ideally, as part of your initial commit. This helps to prevent accidentally committing unwanted files to the repository.

2. Customize .gitignore for your project

While there are common patterns and files to ignore across many projects (e.g., log files, temporary files), each project might have specific needs. Customize your .gitignore file based on the languages, frameworks, and tools you use.

3. Use comments for clarity

Use comments in your .gitignore file (lines starting with #) to explain why certain files or directories are ignored. This practice is particularly helpful for new team members or when revisiting a project after some time.

4. Leverage global .gitignore for personal files

Use a global .gitignore file for ignoring files specific to your development environment (like editor backup files, operating system files, etc.), so you don’t need to pollute project .gitignore files with personal preferences.

5. Avoid ignoring files retroactively

If a file has already been committed to your Git repository, simply adding it to .gitignore will not remove it from the repository or its history. You need to explicitly remove the file from the repository, commit that change, and then ensure it's ignored moving forward. Here’s how to retroactively ignore files that have already been committed:

Step 1: Add the file to .gitignore

First, make sure to add the filename or pattern matching the file you want to ignore to the .gitignore file in the root of your repository. This step prevents the file from being tracked in future operations once it's removed.

Terminal

# Example .gitignore entry

path/to/your/file.txt

Step 2: Remove the file from the repository

Use the git rm --cached command to remove the file from the repository while keeping it in your working directory. The --cached option is crucial because it only removes the file from the index (staging area) and not your local file system.

Terminal

git rm --cached path/to/your/file.txt

If the file is located in multiple places or you're removing all files of a certain type, you might use wildcards. For example, to remove all .log files:

Terminal

git rm --cached *.log

Or, if you need to remove a directory (and its contents) from the repository but keep it locally, use the -r flag:

Terminal

git rm --cached -r path/to/your/directory/

Step 3: Commit the change

After removing the file(s) from the repository, you need to commit this change. This action records the removal of the file from the tracked content of the repository.

Terminal

git commit -m "Remove file.txt from the repository"

Step 4: Push your changes

Finally, push your changes to the remote repository to ensure that the file removal is reflected in the remote repository as well.

Terminal

git push origin your_branch_name

Additional notes

  • Historical data: Removing a file like this will prevent it from being tracked in future commits, but it does not alter the history. Previous commits will still contain the file. If you need to remove the file from the entire history of the repository (for example, if it contains sensitive data), you will need to use more complex techniques like git filter-branch, git rebase, or the BFG Repo-Cleaner tool.

  • Collaborators: If you're working with a team, inform your collaborators about the change. They'll need to pull the latest commits to sync their local repositories with the remote repository.

6. Should you commit .gitignore in your repository?

Yes, you should commit the .gitignore file to your remote repository. This ensures that all contributors to the project are on the same page regarding which files should not be tracked by Git.

Is .gitignore generated by default?

No, .gitignore is not generated by default when you create a new Git repository. However, many project templates, frameworks, and platforms (like GitHub when creating a new repository via the web interface) offer to include a .gitignore file tailored for specific project types.

Example of a standard .gitignore file

Below is an example of a .gitignore file for a python project. It includes common directories and files that should not be tracked by Git in most python projects:

Terminal

# Byte-compiled / optimized / DLL files

__pycache__/

*.py[cod]

*$py.class

# C extensions

*.so

# Distribution / packaging

.Python

build/

develop-eggs/

dist/

downloads/

eggs/

.eggs/

lib/

lib64/

parts/

sdist/

var/

wheels/

pip-wheel-metadata/

share/python-wheels/

*.egg-info/

.installed.cfg

*.egg

# PyInstaller

# Usually these files are written by a python script from a template

# before PyInstaller builds the exe, so as to inject date/other infos into it.

*.manifest

*.spec

# Installer logs

pip-log.txt

pip-delete-this-directory.txt

# Unit test / coverage reports

htmlcov/

.tox/

.nox/

.coverage

.coverage.*

.cache

nosetests.xml

coverage.xml

*.cover

.hypothesis/

.pytest_cache/

pytestdebug.log

# Translations

*.mo

*.pot

# Django stuff:

*.log

local_settings.py

db.sqlite3

db.sqlite3-journal

# Flask stuff:

instance/

.webassets-cache

# Scrapy stuff:

.scrapy

# Sphinx documentation

docs/_build/

This .gitignore file example illustrates patterns for ignoring Python bytecode files, distribution packages, coverage reports, and various configuration files that should not be tracked in a Python-based project's Git repository.

If you are having problems with your .gitignore file not behaving the way you expect it to, see this guide on troubleshooting .gitignore files.

For further reading about the intricacies of the .gitignore file see the official git documentation.

How to use a .gitignore file (2024)

FAQs

How do I use gitignore for files? ›

Configuring ignored files for a single repository
  1. Open Terminal .
  2. Navigate to the location of your Git repository.
  3. Create a .gitignore file for your repository. touch .gitignore. If the command succeeds, there will be no output.

Why won't my gitignore work? ›

Incorrect Syntax or Patterns

Typos or incorrect syntax in the . gitignore file can render rules ineffective, leading to unintended tracking or ignoring of files. Solution: Carefully review and correct the syntax. Ensure that each pattern is on a new line for clarity.

How do I ignore everything except in gitignore? ›

Make . Gitignore Ignore Everything except a Few Files
  1. Open or create a . gitignore file in the root directory of your Git repository.
  2. Add the following patterns to ignore everything except the files you want to include: Copied! # Ignore everything * # Except the following files ! file1.txt ! ...
  3. Save the . gitignore file.
Jun 24, 2024

What should I ignore in gitignore? ›

Global Git ignore rules

You should be careful what patterns you choose to globally ignore, as different file types are relevant for different projects. Special operating system files (e.g. .DS_Store and thumbs.db ) or temporary files created by some developer tools are typical candidates for ignoring globally.

How do I ignore files inside a folder in gitignore? ›

gitignore can also be used to ignore entire directories, along with any files and subdirectories in the directory. To ignore a specific directory, append a / symbol to the end of the directory name.

How to open .gitignore file? ›

You can open the file with your chosen text editor. You can also use the git check-ignore pathname command to see whether a particular file is on the ignore list.

How to know if gitignore is working? ›

You can use the git check-ignore command to verify if your file is gitnored. It will tell you also which gitignore if you have multiple and which line. The -v is a verbose flag and gives us the line number and the actual . gitignore which is useful information to have.

Does gitignore need to be in every folder? ›

gitignore file is a plain text file where each line contains a pattern for files/directories to ignore. Generally, this is placed in the root folder of the repository, and that's what I recommend. However, you can put it in any folder in the repository and you can also have multiple .

How do I ignore a gitignore file itself? ›

Also, you can make the . gitignore file "ignore itself" so that it's not posted publicly and works normally - but it's possible only if it was created manually, touch . gitignore.

Is gitignore automatically ignored? ›

the automatic exclusion of ignored files via . gitignore should work in all repository roots. Ideally when selecting a . gitignore file and using the automatic exclusion then only files in that repository root should be considered.

What does .gitignore do? ›

gitignore file is used in a git repository to ignore the files and directories which are unnecessary to project this will be ignored by the git once the changes as been committed to the Remote repository.

How do I ignore all .class files in gitignore? ›

Use the asterisk (“*”) as a wildcard. For example, “*. class” will ignore all files that have the “. class” extension.

Why doesn't gitignore work? ›

If you have nested Gitignore files in different directories within your repository, Git may not be able to properly interpret the patterns, leading to Gitignore not working as expected. To fix this issue, you can use the ! (exclamation mark) character in your Gitignore patterns to specify exceptions.

How do I add .gitignore to a repository? ›

Creating a . gitignore file:
  1. Open your text editor or code editor of choice.
  2. Create a new file in the root directory of your Git repository.
  3. Save the file with the name “. ...
  4. You're now ready to specify the files and directories that you want Git to ignore.
Apr 8, 2024

When should I use gitignore? ›

The purpose of gitignore files is to ensure that certain files not tracked by Git remain untracked. To stop tracking a file that is currently tracked, use git rm --cached to remove the file from the index. The filename can then be added to the .gitignore file to stop the file from being reintroduced in later commits.

How to create a .gitignore file? ›

Step 1: Install the gitignore extension for VSCode. Step 2: Open the command palette using Ctrl+Shift+P and type Add gitignore. Step 3: Select the framework or the language of your project, and the extension will generate the . gitignore file for you.

How to hide files in gitignore? ›

To create a Git Ignore File, save an empty file named . gitignore into the base folder of your Git repo using your code editor. Files starting with a period (.) are hidden in Unix-based operating systems like macOS.

How do I manually add a gitignore file? ›

Creating a . gitignore file:
  1. Open your text editor or code editor of choice.
  2. Create a new file in the root directory of your Git repository.
  3. Save the file with the name “. ...
  4. You're now ready to specify the files and directories that you want Git to ignore.
Apr 8, 2024

How do I remove a file and add it to gitignore? ›

Remove the file from Git version control using the git rm command:
  1. git rm --cached file.txt.
  2. git commit -m "Remove file.txt from Git tracking"
  3. git add .gitignore git commit -m "Add file.txt to .gitignore"
Jun 6, 2023

References

Top Articles
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated:

Views: 5525

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.