Setting Up a .gitignore File
What is a .gitignore File?
A .gitignore file is a text file used in Git repositories to specify files or directories that should be ignored by Git. This means that any file patterns listed in the .gitignore file will not be tracked, staged, or committed to the repository.
Why is .gitignore Important?
It is especially useful for excluding temporary or sensitive files, such as build artifacts, logs, and configuration files that are specific to your local, staging, or production environment. For example, it ensures files like API keys, passwords, or environment variables (e.g., .env files) are not accidentally committed and exposed to others.
How to Include a .gitignore File?
In my tutorial, Structuring Python Project Directories, we set up a dedicated folder to store the source code. Let us use the Gen EMR project as an example. Open up your terminal and navigate to the directory below:
1 2 3 |
|
1. Create a .gitignore file
In your project’s source code directory, create a file named .gitignore
.
1 2 3 4 |
|
2. Add file patterns to ignore
GitHub and Toptal provide an official list of recommended .gitignore files for various operating systems, environments, and languages. For details, check out github/gitignore or gitignore.io.
We will use the .gitignore file for Python projects suggested by GitHub.
A snippet below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
What are the .gitignore Patterns?
Pattern | Description | Example |
---|---|---|
# |
Comment | # Django stuff |
file_name |
Ignores a specific file. | example.txt will be ignored. |
directory_name/ |
Ignores a specific directory and its contents. | django_project/sent_emails/ will be ignored. |
* |
Matches zero or more characters. | *.log will make abc.log and 123.log be ignored. |
? |
Matches a single character. | file_?.txt will make file_a.txt and file_1.txt be ignored. |
** |
Matches files and directories recursively at any level. |
**/abc will make any file or directory named abc be ignored anywhere. abc/** will make any files inside abc directory be ignored. a/**/b will make directories such as a/b, a/x/b, and a/x/y/b be ignored. |
! |
Excludes files from being ignored even if they match another pattern | !include_me.log will make include_me.log to be tracked even if previously ignored. |
\ |
Escapes special characters like !, #, or *. | \#include_me.txt will make #include_me.txt to be ignored. |