Gitignore in Git
In Git, a .gitignore file is used to tell Git which files or directories to ignore in a repository. This is helpful for excluding files that you don't want to track or commit, such as temporary files, compiled code, build artifacts, or sensitive information like passwords.
How to use .gitignore:
Create a
.gitignorefile:In your project’s root directory, create a file named.gitignore(with no extension). You can create this file manually or through the command line:touch .gitignoreAdd files and directories to ignore:Open the
.gitignorefile and list the files or directories you want Git to ignore. Each pattern should be on a new line. For example:# Ignore all .log files*.log# Ignore node_modules directorynode_modules/# Ignore all .env files.env# Ignore macOS system files.DS_StoreGitignore patterns:
*.log– Ignores all files ending with.log.directory/– Ignores a specific directory (e.g.,node_modules/)..env– Ignores a specific file (e.g.,.env)./file_name– Ignores a file in the root directory, but not in subdirectories.!pattern– Negates a pattern and forces Git to include a file that would normally be ignored.
Example .gitignore:
# Ignore system files.DS_StoreThumbs.db# Ignore IDE settings.idea/.vscode/# Ignore node_modules (for Node.js projects)node_modules/# Ignore Python bytecode*.pyc# Ignore environment files.env# Ignore log files*.log
Applying
.gitignore:- If a file is already being tracked by Git, adding it to
.gitignorewon't remove it from the Git history. You'll need to remove it manually:git rm --cached <file>
- If a file is already being tracked by Git, adding it to
Committing
.gitignore:Once you've set up your.gitignorefile, add and commit it to your repository:git add .gitignoregit commit -m "Add .gitignore file"
Useful tips:
If you want to ignore all files in a directory except one, use
!to include the specific file:/build/*!/build/important-file.txtThere are also global
.gitignorefiles that can be used for all Git repositories on your system. You can set this up with:git config --global core.excludesfile ~/.gitignore_global
You can find templates for common .gitignore files for different programming languages and environments on the GitHub Gitignore repository.