Git .gitattributes and Line Endings

Updated · 11 min read
mediumGit 2.53gitgitattributesline-endingscrlfmerge-driverinterview

.gitattributes is a file in the repository that assigns attributes to paths, telling Git how to handle each kind of file: whether it is text (and how its line endings are stored), whether it is binary, which program diffs or merges it, and whether it belongs in release archives. Unlike settings in .gitconfig, which belong to one person, .gitattributes is committed, so every clone treats files the same way. Its best-known use is ending the long-standing trouble with line endings between Windows, macOS and Linux.

A school library puts colored labels on its books: red for reference books that can't be borrowed, blue for magazines that are thrown away each year. The labels travel with the books, so every librarian handles them the same way. .gitattributes labels files for Git.

Syntax

Each line has a path pattern (as in .gitignore) followed by one or more attributes:

.gitattributes
# pattern       attributes
*               text=auto
*.java          text diff=java
*.sh            text eol=lf
*.bat           text eol=crlf
*.png           binary
CHANGELOG.md    merge=union
docs/drafts/**  export-ignore
AttributeDescription
text=autoIt is used to let Git detect text files and store them with LF line endings.
text / -textIt is used to force a file to be treated as text, or never as text.
eol=lf / eol=crlfIt is used to fix the line ending in the working tree, whatever the operating system.
binaryIt is used to mark a file as binary: no line-ending changes, no text diff, no text merge.
diff=<driver>It is used to choose how diffs and hunk headers are shown (such as java). -diff shows no content diff.
merge=<driver>It is used to choose how the file is merged (union keeps both sides' lines).
export-ignoreIt is used to leave the path out of git archive.
linguist-*It is used to give GitHub hints for its language statistics, such as linguist-generated.

The Line-Ending Problem

Text files end each line with invisible characters: LF (\n) on macOS and Linux, and CRLF (\r\n) on Windows. If Navika works on Windows and Srihitha on Linux, and nothing is configured, every line of a file one of them edited may look changed to the other, diffs become useless, and merges conflict on every line.

The solution is to store LF in the repository and convert at the edges: text files get the operating system's line ending when checked out, and LF again when committed. * text=auto in .gitattributes turns this on for the whole team.

Terminal
mkdir fee-tracker
cd fee-tracker
git init --quiet
echo "* text=auto" > .gitattributes
printf 'Term 1 fee: $12,000\r\nLate fee: $250\r\n' > fees-windows.txt
printf 'Term 1 fee: $12,000\nLate fee: $250\n' > fees-linux.txt
git add .
git commit --quiet -m "Add fee lists from two computers"
git ls-files --eol
Output
warning: in the working copy of 'fees-windows.txt', CRLF will be replaced by LF the next time Git touches it
i/lf    w/lf    attr/text=auto        	.gitattributes
i/lf    w/lf    attr/text=auto        	fees-linux.txt
i/lf    w/crlf  attr/text=auto        	fees-windows.txt

Explanation: git ls-files --eol shows, for each file, the line endings in the index (i/) and in the working tree (w/), and the attribute that applies. fees-windows.txt has CRLF in the folder (w/crlf), but was stored with LF (i/lf), because text=auto normalized it. Both files are now identical in the repository, whichever computer they came from. The warning from git add says the same thing: the file in your folder still has CRLF, and the next time Git writes it there (for example on checkout), it will get this computer's ending.

SettingEffect
* text=auto in .gitattributesRecommended. Committed, so it applies to every clone the same way
core.autocrlf trueWindows only: convert to CRLF on checkout, to LF on commit. A personal setting
core.autocrlf inputmacOS and Linux: convert CRLF to LF on commit, never back
core.eolWhich ending to use in the working tree for text files without eol (default: the system's)

core.autocrlf is a per-person setting that each team member must remember, and it is the source of many "it changes every line" surprises. A committed .gitattributes makes the behavior part of the project.

Adding .gitattributes to an Existing Project

Files committed before the rule are not converted automatically. After adding .gitattributes, run git add --renormalize . once and commit, so that every file is stored with LF from then on:

Terminal
cd ..
mkdir old-project
cd old-project
git init --quiet
printf 'Term 1 fee: $12,000\r\n' > fees.txt
git add fees.txt
git commit --quiet -m "Add fees with CRLF"
git ls-files --eol fees.txt
echo "* text=auto" > .gitattributes
git add .gitattributes
git add --renormalize .
git ls-files --eol fees.txt
git commit --quiet -m "Normalize line endings"
rm fees.txt
git restore fees.txt
git ls-files --eol fees.txt
Output
i/crlf  w/crlf  attr/                 	fees.txt
i/lf    w/crlf  attr/text=auto        	fees.txt
i/lf    w/lf    attr/text=auto        	fees.txt

Before, the CRLF file was stored as is (i/crlf, with no attribute). After --renormalize, it is stored with LF (i/lf), but the copy in the folder still has CRLF (w/crlf). Deleting it and restoring it from the index gives a fresh copy with this computer's line ending, LF here (w/lf). Note that this commit touches every line of affected files, so make it a separate commit, and add it to .git-blame-ignore-revs (see "Git Blame").

One line ending in the repository, the right one on each system

Binary Files

Git guesses whether a file is binary by looking for zero bytes. Marking file types explicitly is safer: binary means "never change line endings, never show a text diff, never try a text merge":

Terminal
echo "*.png binary" >> .gitattributes
printf "\x89PNG fake image\r\n" > logo.png
git add .
git commit --quiet -m "Add the logo"
printf "\x89PNG changed image\r\n" > logo.png
git diff --stat
git diff logo.png
Output
 logo.png | Bin 17 -> 20 bytes
 1 file changed, 0 insertions(+), 0 deletions(-)
diff --git a/logo.png b/logo.png
index a045984..2a6990f 100644
Binary files a/logo.png and b/logo.png differ

The diff only says that the binary file changed. Without the attribute, this "image" contains no zero byte, so Git would have treated it as text and changed its \r\n, corrupting a real image.

Merge Drivers: union

Some files are only ever added to, such as a changelog, where each branch adds lines at the end. Two branches adding lines in the same place conflict, although for a file like this, keeping both is the right answer. merge=union tells Git to keep both sides' lines without a conflict:

Terminal
echo "CHANGELOG.md merge=union" >> .gitattributes
echo "# Changes" > CHANGELOG.md
git add .
git commit --quiet -m "Add the changelog"
git switch --quiet -c feature/late-fee
echo "- Late fee added" >> CHANGELOG.md
git commit --quiet -am "Note the late fee"
git switch --quiet main
echo "- Hostel fee added" >> CHANGELOG.md
git commit --quiet -am "Note the hostel fee"
git merge --quiet --no-edit feature/late-fee
cat CHANGELOG.md
Output
Auto-merging CHANGELOG.md
# Changes
- Hostel fee added
- Late fee added

Explanation: both branches added a line at the same place, which would normally conflict. With merge=union, Git kept both lines and finished the merge. Use it only for files where the order of lines doesn't matter and duplicates are harmless: on code, it can silently produce invalid results.

Leaving Files Out of Archives: export-ignore

git archive (and the "Download ZIP" buttons of hosting platforms) packages a commit's files. export-ignore keeps paths out, such as internal notes or CI configuration:

Terminal
mkdir notes
echo "internal planning" > notes/plan.txt
echo "notes/** export-ignore" >> .gitattributes
git add .
git commit --quiet -m "Add planning notes"
git archive HEAD | tar -t
Output
.gitattributes
CHANGELOG.md
fees.txt
logo.png
notes/

notes/plan.txt is in the repository, but not in the archive. Only an empty notes/ folder entry is left, because the pattern notes/** matches the files inside, not the folder. notes export-ignore would leave out the folder itself. (.gitattributes itself is in it. Add .gitattributes export-ignore too if you don't want it shipped.)

Checking Attributes

git check-attr shows which attributes apply to a path, which helps when a rule doesn't seem to work:

Terminal
git check-attr -a CHANGELOG.md logo.png notes/plan.txt
Output
CHANGELOG.md: merge: union
CHANGELOG.md: text: auto
logo.png: binary: set
logo.png: diff: unset
logo.png: merge: unset
logo.png: text: unset
notes/plan.txt: text: auto
notes/plan.txt: export-ignore: set

Common Mistakes

Relying on each person's core.autocrlf. One forgotten setting, and a commit changes every line. Commit * text=auto instead.

Adding .gitattributes without renormalizing. Old files keep their CRLF in the repository. Run git add --renormalize . once.

CRLF shell scripts. bad interpreter: /bin/sh^M means a script has CRLF. Add *.sh text eol=lf and renormalize.

Unmarked binary types. Unusual binary formats may be mistaken for text and have bytes changed. List them with binary.

merge=union on source code. It can merge two conflicting edits into nonsense without telling you. Use it only for append-only lists.

Under the Hood

Git applies attributes at two moments, called clean and smudge. When content goes into the repository (git add), the clean step runs: for text files, CRLF becomes LF. When content comes out (checkout, git restore), the smudge step runs: for text files, LF becomes the working tree's line ending. A filter=<name> attribute plugs custom programs into these steps, which is exactly how Git LFS works: its clean filter swaps a large file for a small pointer, and its smudge filter downloads the real file (see the lessons on large repositories). Attributes are read from .gitattributes files in every folder (the closest one wins), from .git/info/attributes for private rules, and from the file named by core.attributesFile for global ones.

Interview Corner

What is .gitattributes used for?

To assign attributes to paths: line-ending handling (text, eol), binary files, diff and merge drivers, export rules (export-ignore), filters such as Git LFS, and hosting-platform hints. It is committed, so all clones behave the same.

How do you fix line-ending problems between Windows and Linux developers?

Commit a .gitattributes with * text=auto (plus eol=lf for scripts and eol=crlf for batch files), then run git add --renormalize . and commit. The repository then stores LF, and each checkout uses the right ending.

What is the difference between core.autocrlf and .gitattributes?

core.autocrlf is a personal setting each developer must configure. .gitattributes rules are committed with the project and apply to everyone, so they are more reliable, and they override core.autocrlf for the paths they cover.

What does merge=union do?

It merges a file by keeping the lines from both sides instead of reporting a conflict. It suits append-only files like changelogs, but is unsafe for code.

Practice

Challenge: a script with the wrong endings. Add a rule that shell scripts always use LF, create build.sh with CRLF line endings (printf "echo build\r\n"), stage it, and print its --eol information.

What does Git print? Before you open the solution, decide which line ending build.sh gets in the index, and which attribute git ls-files --eol reports.

Show solution
Terminal
echo "*.sh text eol=lf" >> .gitattributes
printf "echo build\r\n" > build.sh
git add .gitattributes build.sh
git ls-files --eol build.sh
Output
warning: in the working copy of 'build.sh', CRLF will be replaced by LF the next time Git touches it
i/lf    w/crlf  attr/text eol=lf      	build.sh

It is stored with LF (i/lf), and the attribute column shows text eol=lf. On every computer, the checked-out script will have LF, so Linux and macOS can run it.

Checkpoint. Add a .gitattributes to a project of your own with * text=auto, rules for scripts and binaries, and *.java diff=java. Run git add --renormalize ., look at git ls-files --eol, and commit the normalization separately.

Quick check: .gitattributes

4 questions
1Which line normalizes line endings for all text files?
2After adding .gitattributes to an old project, which command converts the files already committed?
3What does binary do?
4Which attribute keeps a folder out of git archive?

Key Takeaways

Quick reference

Command or ruleIt is used to
* text=autoNormalize line endings
*.sh text eol=lfKeep scripts LF everywhere
*.png binaryMark binary files
git add --renormalize .Apply new rules to committed files
git ls-files --eolShow line endings in the index and working tree
git check-attr -a <path>Show the attributes of a path

Was this tutorial helpful?

Lesson 79 of 106