Complete Guide to the `.gitignore` File (2024)

Adrián Bailador

Posted on

#git #webdev #programming #dotnet

Introduction

The .gitignore file is an essential tool in any Git repository. It allows you to specify which files or directories should not be tracked by Git, helping to keep the repository clean and free of unnecessary files.

Creating a .gitignore File

Creating a .gitignore file is as simple as creating a new text file in the root of your repository with the name .gitignore.

Tools for .gitignore

There are several tools and online resources that can help you generate an appropriate .gitignore file for your project. Some of them are:

What Should I Ignore?

Generally, you should ignore files that are not necessary for the operation of your project or that can be generated from the source code. Some common examples are:

  • Local configuration files
  • Build directories
  • Binary and executable files
  • Logs and data files
  • Downloaded dependencies (like node_modules in Node.js projects)

How to Ignore Different Files and Directories

To ignore specific files or directories, simply add their path to the .gitignore file. For example:

# Ignore the config.json fileconfig.json# Ignore all .log files in the logs directorylogs/*.log# Ignore the entire build directorybuild/

Using the * Character

The * character in a .gitignore file is used as a wildcard that can match any string of characters. For example, *.log will ignore all files ending in .log.

Checking the .gitignore File

To check if your .gitignore file is working correctly, you can make a change to a file that should be ignored and then run git status. If the file does not appear in the list of changes, then your .gitignore file is working correctly.

Forgetting to Add a File to .gitignore

If you forget to add a file to .gitignore and it has been previously tracked by Git, you will need to remove it from the repository with:

git rm --cached <file>

Then add it to .gitignore and commit the changes:

echo <file> >> .gitignoregit add .gitignoregit commit -m "Add <file> to .gitignore"

Reverting a File that is Already in .gitignore

If you have ignored a file in .gitignore but then decide you want to track it, you can do so by removing the corresponding entry from the .gitignore file. Then, you can add the file to the repository with git add <file> and commit the changes.

Matching Patterns in .gitignore

Matching patterns in .gitignore allow you to specify which files to ignore. Some examples are:

  • *.log: Ignores all files ending in .log.
  • !/important.log: Does not ignore the important.log file.
  • debug/: Ignores all files in the debug directory.
  • **/debug/*: Ignores all files in any directory named debug.

Negative Patterns in .gitignore

Negative patterns in .gitignore allow you to specify exceptions to the ignore rules. They are indicated with a ! at the beginning. For example, if you want to ignore all .log files except important.log, you can do it like this:

*.log!/important.log

Ignoring Only Some Files Within a Directory

If you want to ignore only some files within a directory, you can specify them directly in the .gitignore file. For example, if you want to ignore only .txt files in the docs directory, you can do it like this:

docs/*.txt

Ignoring Files in a Specific Branch

Git does not allow ignoring files in a specific branch directly through the .gitignore file. However, you can create different .gitignore files in different branches. Note that if you merge these branches, you will have to resolve conflicts in the .gitignore file.

Excluding an Entire Directory

To exclude an entire directory, simply add the directory name followed by a / to the .gitignore file. For example, to exclude the entire node_modules directory, you can do it like this:

node_modules/

Examples of .gitignore for Common Technologies

.NET

bin/obj/*.user*.suo*.rsuser*.vscode/

Angular

/dist/node_modules/.env/.idea/.vscode

React

/node_modules/.env/build/coverage.vscode/.idea/

Python

__pycache__/*.py[cod]*.pyo.env.venv.mypy_cache/.pytest_cache/

Java

*.class*.jar*.war*.eartarget/

Node.js

node_modules/npm-debug.logyarn-error.log

Ordering and Organizing .gitignore

Keeping the .gitignore file ordered and organized, especially in large projects, is crucial. Grouping rules by file type or directory makes it easier to read and maintain.

Integration Tools

There are tools that integrate with Git and can automatically generate or manage the .gitignore file, such as some Visual Studio Code extensions and plugins for popular IDEs.

Behavior in Subdirectories

The .gitignore file in a subdirectory applies only to files in that subdirectory and its subdirectories. This allows for specific rules for different parts of the project.

Versioning the .gitignore File

It is important to version and share the .gitignore file with the development team to ensure that everyone works with the same ignore rules.

Advanced Usage Example

Provide an example of advanced usage, such as ignoring all files except one in a directory:

# Ignore all files in logs except important.loglogs/*!logs/important.log

Possible Confusions and Common Mistakes

List some common errors when using .gitignore, such as forgetting to add the / at the end of a directory or not updating the .gitignore file after significant changes to the project structure.

Including Locally Generated Files

Locally generated files, such as editor configuration files (.vscode/, .idea/) and environment files (.env), should generally be ignored to avoid conflicts between developers using different local configurations.

Comments in .gitignore

Comments in .gitignore can be made using the # character at the beginning of a line. Comments are useful for explaining the purpose of certain ignore rules.

Ignoring File Types Across the Repository

To ignore a file type across the repository, you can use *.log to ignore all .log files anywhere in the repository.

Forcing Tracking of Ignored Files

Sometimes, you may want to force Git to track a file that is normally ignored. This can be done with git add -f <file>.

Checking Ignored Files

You can use the git check-ignore utility to check which rule in the .gitignore file is causing a specific file to be ignored.

Global .gitignore Files

Git also allows for a global .gitignore file to ignore certain files across all repositories on a machine. This can be useful for ignoring, for example, OS-specific or text editor-specific files.

Ignoring Files without Including them in .gitignore

You can use the .git/info/exclude file, which allows you to ignore files similar to .gitignore, but without including the ignore rules in the repository.

Additional Resources and Readings

Provide links to additional resources and documentations:

Conclusion

The .gitignore file is an indispensable tool for managing which files should be ignored by Git, ensuring that only necessary files are tracked and versioned. By mastering the use of .gitignore, you can keep your repository clean and avoid common issues stemming from unnecessary or environment-specific files. Taking advantage of available tools and resources, such as .gitignore generators and templates, will help you create an effective and appropriate .gitignore file for your project. Remember to always version this file and share it with your team to maintain consistency in ignore rules.

Complete Guide to the `.gitignore` File (2024)

FAQs

How to .gitignore a file? ›

If you want to ignore a file that you've committed in the past, you'll need to delete the file from your repository and then add a .gitignore rule for it. Using the --cached option with git rm means that the file will be deleted from your repository, but will remain in your working directory as an ignored file.

What should I put in my gitignore? ›

Items to put in the . gitignore
  1. System-specific files. System-specific files need to get ignored. ...
  2. Vscode workspaces. Items like a vscode workspace need to be ignored.
  3. Security and API keys/secrets. For security, the security key files and API keys should get added to the gitignore.
Aug 5, 2020

How to list all existing files ignored by git? ›

You can use git ls-files --others --ignored --exclude-standard to list untracked files that were ignored by the rules in your . gitignore .

How to use gitignore to ignore a folder? ›

How to Add Folders to 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 should a gitignore file look like? ›

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.

How do I add .gitignore to a repository? ›

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.

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.

How does .gitignore work? ›

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.

Should the .gitignore file be tracked? ›

Yes, you can track the . gitignore file, but you do not have to. The main reason of having this file into repository is to have everyone working on the project, ignoring same files and folders.

Why is .gitignore not ignoring my files? ›

Git is case-sensitive, and discrepancies in case between . gitignore rules and actual file names can lead to incorrect inclusion or exclusion. Solution: Ensure that the case in . gitignore rules precisely matches the actual case of files and directories in the repository.

Does .gitignore need to be in root? ›

Typically, a .gitignore file gets placed in the root directory of the repository. The root directory is also known as the parent and the current working directory. The root folder contains all the files and other folders that make up the project.

What is the difference between gitignore and exclude? ›

gitignore are to be shared among project members (i.e. everybody working on the project should consider the paths that match the ignore pattern in there as cruft). On the other hand, . git/info/exclude is meant for personal ignore patterns (i.e. you, while working on the project, consider them as cruft).

How to hide a file using 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 exclude a file from tracking in git? ›

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 do I remove a specific file from 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

How do I remove a file from git? ›

Delete a file from a Git repository
  1. git rm unwanted-file.txt. This command will delete the file and stage its deletion to be included in the next commit. ...
  2. git rm --cached unwanted-file.txt. ...
  3. git filter-repo -f --index-filter 'git rm --cached --ignore-unmatch unwanted-file.txt'
Apr 15, 2023

References

Top Articles
Latest Posts
Article information

Author: Amb. Frankie Simonis

Last Updated:

Views: 6347

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Amb. Frankie Simonis

Birthday: 1998-02-19

Address: 64841 Delmar Isle, North Wiley, OR 74073

Phone: +17844167847676

Job: Forward IT Agent

Hobby: LARPing, Kitesurfing, Sewing, Digital arts, Sand art, Gardening, Dance

Introduction: My name is Amb. Frankie Simonis, I am a hilarious, enchanting, energetic, cooperative, innocent, cute, joyous person who loves writing and wants to share my knowledge and understanding with you.