How to Fix Line Ending Issues in Git Quickly
git config --global core.autocrlf properly and adding a .gitattributes file to enforce consistent endings.Why This Happens
Windows uses CRLF (Carriage Return + Line Feed) for line endings, while Unix/Linux/macOS use LF (Line Feed) only. When you share code across these systems, Git can show changes or conflicts just because of these differences, not actual code changes.
This happens because Git tracks line endings literally, so mismatched endings look like file changes.
echo "line1\r\nline2\r\n" > file.txt # Windows-style CRLF endings # Git sees this as different from LF endings:
The Fix
Set Git to handle line endings automatically by configuring core.autocrlf. On Windows, use true to convert LF to CRLF on checkout and back to LF on commit. On macOS/Linux, use input to keep LF endings.
Also, add a .gitattributes file to enforce consistent line endings per file type.
# For Windows users git config --global core.autocrlf true # For macOS/Linux users git config --global core.autocrlf input # Create .gitattributes file echo "* text=auto" > .gitattributes git add .gitattributes git commit -m "Add .gitattributes to normalize line endings"
Prevention
Always set core.autocrlf correctly before cloning repositories. Use a .gitattributes file in your project to define line ending rules for all contributors. This avoids line ending conflicts and keeps your code consistent.
- Use
* text=autoin.gitattributesfor general text files. - Specify binary files with
-textto avoid conversion. - Check line endings with editors that show invisible characters.
Related Errors
Other common Git issues related to line endings include:
- Unwanted file changes: Git shows files as changed due to line ending differences.
- Merge conflicts: Line ending mismatches cause confusing conflicts.
- Binary files corrupted: If line endings are converted on binary files, they get corrupted.
Fix these by using .gitattributes to mark binary files with -text and normalizing line endings.