How to Use .gitignore to Ignore Files and Folders in Git
How to Use .gitignore to Ignore Files and Folders in Git
When working withGit, it is essential to manage which files should be tracked and which should be ignored. Tracking files that should be ignored can clutter the repository, increase storage requirements, and even pose security risks. To solve this problem, Git provides a.gitignorefile, which allows developers to specify files and folders that should be excluded fromversion control.
This guide will cover how to use the.gitignorefile to exclude files and folders in Git. We’ll also discuss its benefits, common ignore patterns, and best practices for effective usage.
Firstly, let’s discuss what Git ignore is and how it works.
What is a.gitignorefile in Git?
The.gitignorefile is a feature in Git that specifies the files and folders that should not be tracked by Git. This is useful for preventing unnecessary or sensitive files and folders from being included in a repository, such as log files, environment configuration files, and build artifacts.
By defining patterns in.gitignore, developers can ensure that specific files remain untracked by Git. Once a file is ignored, Git will not include it incommits, preventing it from being pushed toremote repositories. This helps keep the repository clean, ensures sensitive data is not accidentally exposed, and improves overall efficiency in collaboration.
Next, let’s have a look at the advantages of using.gitignore.
Advantages of using git ignore
There are several advantages of using.gitignore:
- Keeps the Repository Clean: Prevents clutter by excluding unnecessary files like compiled binaries, cache files, and system-generated files.
- Enhances Collaboration: Ensures teammates don’t accidentally commit personal or machine-specific files, making the repository cleaner and more consistent.
- Avoids Merge Conflicts: Prevents merge conflicts caused byIDE-specific files or user-generated temporary files.
- Security and Privacy: Helps prevent committing sensitive data like API keys, passwords, or private configuration files.
Now that we’re aware of the benefits of.gitignore, let’s go through the step-by-step process of creating a.gitignorefile.
How to create a.gitignorefile
Creating a.gitignorefile is straightforward. But before we do that, we need to set up a Git repository on our local machine, which we’ll work on.
Setting up a Git repository
Follow these steps to set up a local Git repository:
1. Open theterminaland run these commands to create and navigate into a new folder nameddemo:
mkdir democd demo
Copy to clipboard
mkdir democd demo
2. Initialize a Git repository inside thedemofolder:
git init
Copy to clipboard
git init
3. Create sample files and folders for the.gitignoredemonstration:
mkdir build subdir1 subdir2 subdir3touch 1.bak 1.txt 2.txt 3.txt 1.log 2.log 3.log build/temp.bin subdir1/main.bin subdir2/temp.bin subdir3/temp.bin
Copy to clipboard
mkdir build subdir1 subdir2 subdir3touch 1.bak 1.txt 2.txt 3.txt 1.log 2.log 3.log build/temp.bin subdir1/main.bin subdir2/temp.bin subdir3/temp.bin
Here, the ones starting with the extensions.bak,.txt,.log, and.binare file names. On the other hand,buildand the ones starting withsubdirare folder names.
The next step to do is to create a.gitignorefile. Let’s see how to do it.
Creating a.gitignorefile
To create a.gitignorefile in thedemorepository, run this command in the terminal:
touch .gitignore
Copy to clipboard
touch .gitignore
Now, we’re ready for the Git ignore demonstration. Let’s start by learning how to ignore a file using.gitignore.
How to ignore a file using.gitignorefile
In this section, we’ll discuss how to use.gitignoreto ignore a specific file or all files of a specific type and add a file as an exception in a Git repository.
Let’s start by discussing how to ignore a specific file using.gitignore.
How to ignore a specific file
To ignore a specific file, run this command in the terminal while in thedemorepository:
git status
Copy to clipboard
git status
Thegit statuscommand displays the status of the repository, listing tracked and untracked files. Here is the current list of untracked files shown in the output:
Untracked files: (use "git add <file>..." to include in what will be committed) .gitignore 1.bak 1.log 1.txt 2.log 2.txt 3.log 3.txt build/ subdir1/ subdir2/ subdir3/
Copy to clipboard
Untracked files: (use "git add <file>..." to include in what will be committed) .gitignore 1.bak 1.log 1.txt 2.log 2.txt 3.log 3.txt build/ subdir1/ subdir2/ subdir3/
Notably, if we ignore any file or folder from this list, it will be removed from the same, indicating that Git is now ignoring that particular file or folder.
Now, suppose we want to ignore the file named1.bakfrom the list. To do this, open the.gitignorefile in Nano, a usefulcommand-lineeditor:
nano .gitignore
Copy to clipboard
nano .gitignore
Then, insert the file name in it:
1.bak
Copy to clipboard
1.bak
After insertion, pressCtrl+Xto exit the Nano editor,Yto save the changes, andEnterto keep the file name as it is.
This line will ignore any file named1.baklocated anywhere in the repository. Since we only have a single file named1.bakin the repository, that file will be ignored.
However, if there are multiple files with the same name in the repository, all those files will be ignored, which you may not want to do. To avoid this, you can add all those files that you want to track as exceptions in the.gitignorefile. We’ll discuss more on this later.
Next, rungit statusagain to check the list of untracked files:
Untracked files: (use "git add <file>..." to include in what will be committed) .gitignore 1.log 1.txt 2.log 2.txt 3.log 3.txt build/ subdir1/ subdir2/ subdir3/
Copy to clipboard
Untracked files: (use "git add <file>..." to include in what will be committed) .gitignore 1.log 1.txt 2.log 2.txt 3.log 3.txt build/ subdir1/ subdir2/ subdir3/
As we can see, the1.bakfile is no longer on the list, indicating that it is now on the ignore list.
In the next section, we’ll learn how to ignore all files of a specific type.
How to ignore all files of a specific type
Suppose we want to ignore all the files with the.txtextension, i.e.,1.txt,2.txt, and3.txt. To achieve this, open the.gitignorefile in Nano and add this line to it:
*.txt
Copy to clipboard
*.txt
This line suggests that all the files that end with the.txtextension will be ignored. The*symbol matches any number of characters before.txtin a file name, indicating that files can have anything at the beginning of their name but must end with.txt.
After saving the changes and exiting Nano, rungit statusto check if the operation is successful:
Untracked files: (use "git add <file>..." to include in what will be committed) .gitignore 1.log 2.log 3.log build/ subdir1/ subdir2/ subdir3/
Copy to clipboard
Untracked files: (use "git add <file>..." to include in what will be committed) .gitignore 1.log 2.log 3.log build/ subdir1/ subdir2/ subdir3/
As we can see, the list doesn’t contain any files with the.txtextension, meaning the files1.txt,2.txt, and3.txtare all on the ignore list now.
Next, let’s discuss how to add a file as an exception.
How to add a file as an exception
Suppose we want to ignore all the files with the.logextension in the repository except the one named1.log. To do this, open the.gitignorefile in Nano and insert these lines into it:
*.log!1.log
Copy to clipboard
*.log!1.log
As we already know, the first line instructs Git to ignore all the files that end with the.logextension in the repository. In the second line, the!symbol tells Git to override the*.logpattern for the1.logfile. In other words, it suggests Git to ignore all the files that end with the.logextension except the one named1.log. As a result, Git will still track the1.logfile.
Next, save the changes and exit Nano. After that, rungit statusto verify if the ignored files are removed from the list of untracked files:
Untracked files: (use "git add <file>..." to include in what will be committed) .gitignore 1.log build/ subdir1/ subdir2/ subdir3/
Copy to clipboard
Untracked files: (use "git add <file>..." to include in what will be committed) .gitignore 1.log build/ subdir1/ subdir2/ subdir3/
Visibly, all the files with the.logextension have been removed from the list except the1.logfile.
So far, we’ve talked about how to ignore files and add files as exceptions using.gitignorefile, but what about folders?
In the next section, we’ll explore how to ignore a folder using the.gitignorefile.
How to ignore a folder using the.gitignorefile
In this section, we’ll learn how to ignore a specific folder and add a folder as an exception using.gitignore. Let’s start by discussing how to ignore a specific folder.
How to ignore a specific folder
Suppose we want to ignore the folder namedbuild. To achieve this, open the.gitignorefile in Nano and add this line to it:
build/
Copy to clipboard
build/
This line tells Git to ignore any folder namedbuildin the repository, along with their files and subfolders. Since there’s only a single folder namedbuildin the repository, that folder will be ignored. However, just like files, there may be folders that you don’t want to ignore. In this case, you can add them as exceptions in the.gitignorefile, which we’ll discuss later.
Another thing to note is that the/symbol at the end of the folder name is necessary. If we remove it, Git ignores all files and folders with the given name in the repository. So, ensure that you provide the/at the end to only ignore folders.
After saving the changes and exiting Nano, rungit statusto verify the operation:
Untracked files: (use "git add <file>..." to include in what will be committed) .gitignore 1.log subdir1/ subdir2/ subdir3/
Copy to clipboard
Untracked files: (use "git add <file>..." to include in what will be committed) .gitignore 1.log subdir1/ subdir2/ subdir3/
As expected, thebuildfolder is no longer on the list.
Next, we’ll learn how to add a folder as an exception.
How to add a folder as an exception
Suppose we want to ignore all the folders starting withsubdirin the repository except the one namedsubdir1. To do this, open the.gitignorefile in Nano and insert this line into it:
subdir*/!subdir1/
Copy to clipboard
subdir*/!subdir1/
These lines indicate:
- subdir*/ignores all folders that start withsubdiralong with their contents.
- !subdir1/overrides this rule, ensuringsubdir1is still tracked.
Next, save the changes and exit Nano. After that, rungit statusto check if the operation is successful:
Untracked files: (use "git add <file>..." to include in what will be committed) .gitignore 1.log subdir1/
Copy to clipboard
Untracked files: (use "git add <file>..." to include in what will be committed) .gitignore 1.log subdir1/
As we can see, all the folders starting withsubdirhave been removed from the list except the one namedsubdir1.
Finally,addand commit all the untracked changes in the repository:
git add .git commit -m “Initial setup”
Copy to clipboard
git add .git commit -m “Initial setup”
The dot (.) after thegit addcommand tells Git to add all the untracked changes to the staging area. Moreover, the-mflag with thegit commitcommand enables us to write an inline commit message, avoiding the hassle of opening the default text editor and writing the message in it.
Now that we’ve discussed how to ignore files and folders using the.gitignorefile, let’s check out some common Git ignore patterns in the next section.
Common Git ignore patterns
There are some patterns that are commonly used in the.gitignorefile to ignore specific files and folders. These patterns can be divided into several categories:
- System-Specific Files: Operating systems often generate files that shouldn’t be tracked in a repository:.DS_Store(macOS metadata file)Thumbs.db(Windows Explorer thumbnail cache)
- Dependencies: Package managers generate folders for installed dependencies, which should not be committed:node_modules/(Dependencies installed by NPM/Yarn).venv/, venv/(Virtual environments)
- IDE-Specific Files: Integrated Development Environments (IDEs) create configuration files and temporary folders that shouldn’t be versioned:.vscode/(VS Code settings).idea/(Project files from JetBrains IDEs)
- Environment and Secret Files: Sensitive configuration files, such as credentials or environment variables, should never be included in a repository:.env*(Environment variable files)secrets.json,config.json(Sensitive configuration files)
In the next section, let’s discuss some best practices for using Git ignore.
Best practices for using Git ignore
Here are some best practices that we should follow while using Git ignore:
- Set Up.gitignoreat the Start: Setting up a Git ignore file at the start of the project prevents unwanted files from being tracked and ensures a clean repository from the beginning.
- Utilize a Global.gitignoreFile: If there are files you want to ignore across multiple repositories, such as system-generated files or editor configurations, set up a global.gitignorefile to apply these rules universally.
- Regularly Update the.gitignoreFile: As your project evolves, ensure that you keep the.gitignorefile up to date to exclude new unnecessary files.
- Avoid Ignoring Essential Files: Avoid excluding files critical to the project’s functionality, such as required configuration files, dependency manifests, or important documentation.
Applying these best practices will ensure your repository remains well-organized and efficient.
Conclusion
In this tutorial, we learned what Git ignore is and how to use a.gitignorefile to ignore unwanted files and folders in Git. We also went through the advantages, common Git ignore patterns, and best practices for making the most out of Git ignore.
Using Git ignore prevents unnecessary files from being tracked, keeping the repository clean and efficient. It enhances security by avoiding accidental commits of sensitive data and helps prevent merge conflicts caused by system-specific files.
If you want to learn about Git branching and collaboration, check out theLearn Git: Branching and Collaborationcourse on Codecademy.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Complete Payment to Unlock Full Guide & Source Code
You are viewing the 30% preview. Join TopCourseAI Pro to unlock the remaining 70% of this article, unblur all code snippets, and gain full access to all 412 technical projects and guides.
Ready to access the complete step-by-step tutorial?
Gain full unhindered access to all 412 technical projects and guides, unblur all source code snippets, and download runnable scripts.
How to Translate With DeepL
Next BlueprintHow to Use AWS Bedrock: Build AI Chatbots with Console and Python
Related Blueprints & Guides
View all 166 →Android Studio Quick-Start Guide
Android Studio often intimidates beginners, but by learning a few handy shortcuts and getting the lay of the land, we can navigate this powerful development environment with ease.
Developer toolsApache Kafka Tutorial: A Complete Guide for Beginners
Apache Kafkais a well-known distributed event streaming platform designed to efficiently manage real-time data feeds. It was originally developed by LinkedIn in 2011 and later open-sourced. Apache Kafka has gained immens...
Developer toolsBuilding Websites with Wix
Creating a website has never been easier. Previously, making a presentable website meant learning HTML, CSS, andJavaScript. The whole process could take weeks, months, or even years before creating a website that you’re...
Ready to build production-grade AI systems?
Enjoyed this guide? Continue exploring our library of 166+ production blueprints, multi-agent swarms, and autonomous agent systems with 100% unblurred, executable source code.