What is .gitattributes?
The .gitattributes file is a special Git configuration file that controls how Git handles specific files in your repository.
- It can define:
- Line ending rules
- File types (e.g., binary vs text)
- Merge behavior
- Custom diff tools
- Export settings for archives
Why Use .gitattributes
Use .gitattributes when you want to:
- Enforce consistent line endings across different operating systems
- Mark files as binary so Git won’t try to merge them or change line endings
- Enable Git LFS (Large File Storage) for large assets
- Set up custom diff or merge drivers for specific file types
- Control which files are included in archives created by git archive
Creating or Editing .gitattributes
- Go to the root of your repository (or any subfolder if you want local rules).
- Create or edit the .gitattributes file.
- Add rules, one per line, to tell Git how to treat specific files.
Examples
Force Unix Line Endings for All Text Files
*.txt text eol=lf
Standardize Line Endings for Shell Scripts
*.sh text eol=lf
Mark Files as Binary
Marking files as binary prevents Git from modifying or merging them.
*.png binary
Enable Git LFS for Large Files
Tell Git to use LFS to store certain file types:
*.psd filter=lfs diff=lfs merge=lfs -text
Custom Diff Driver
Specify a custom diff driver to improve diff output for certain formats:
*.md diff=markdown
Checking File Attributes
You can see what attributes apply to a file:
git check-attr --all README.md
Advanced Usage
Custom Merge Strategies
Use a custom merge driver for complex files like lock files or Jupyter notebooks:
*.lock merge=lockfile
Exclude Files from Archive
Prevent files from being included when creating archives (tar or zip) using git archive:
docs/* export-ignore
Tips & Best Practices
- Patterns in .gitattributes use the same syntax as .gitignore (wildcards, etc.)
- Place .gitattributes in subfolders to apply rules only there.
- Changing .gitattributes won’t automatically fix already committed files—you may need to re-add them (git add --renormalize .).
- Use git check-attr to debug attribute configurations.