.gitignore is a crucial file in any Git repository. It’s a text file that tells Git which files or directories to ignore in a project.
What is .gitignore?
The .gitignore file is a list of rules for ignoring files in every Git repository
When you have files that you don’t want Git to track, such as backup files, log files, or files generated at runtime like .pyc files in Python, you add patterns for these files to your .gitignore file.
How Does .gitignore Work?
Git checks the .gitignore file from the top level of your repository down to the directory level of the context that’s being processed. The patterns specified in .gitignore apply recursively to the entire directory tree under the directory where the .gitignore file is located. However, you can also specify a global .gitignore file for all your repositories by configuring the ‘core.excludesFile'
setting in your Git configuration.
Pattern Format
Blank lines serve as separators for readability.
Comments start with #.
Glob patterns are used for matching files. For example, *.log
ignores all .log
files.
Negation can be done with !
For example, !important.log
would track a file named important.log
even if *.log
is ignored.
Directories can be ignored by ending the pattern with /
For example, build/
ignores all directories named build.
Precedence of Patterns
If there are multiple .gitignore files in a repository, the patterns are applied in a certain order of precedence:
Patterns read from the command line.
Patterns read from .gitignore files in the same directory as the path or in any parent directory.
Patterns read from $GIT_DIR/info/exclude
.
Patterns read from the file specified by the core.excludesFile
configuration variable.
Common Use Cases
Ignoring build directories (/build
, /out
).
Ignoring files generated by your IDE (.vscode
, .idea
).
Ignoring OS-generated files (.DS_Store on macOS, Thumbs.db on Windows).
Best Practices
Do not use .gitignore to exclude sensitive data. Once committed, removing data from the repository history is difficult.
Do commit your .gitignore file to the repository so that other contributors can benefit from it.
Do use comments in your .gitignore file to explain why certain files are ignored.
Creating a .gitignore File
To create a .gitignore file, simply create a new text file named .gitignore in the root directory of your Git repository. Then, add patterns for files you wish to ignore. You can also find templates for .gitignore files for different programming languages and environments on GitHub.
Checking Ignored Files
To see which files are currently being ignored in your repository, you can use the command:
git status --ignored
GITIGNORE
.gitignore
fileSend download link to: