0
0
GitDebug / FixBeginner · 4 min read

How to Fix Line Ending Issues in Git Quickly

Line ending issues in Git happen because Windows and Unix use different line endings. Fix this by setting 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.

bash
echo "line1\r\nline2\r\n" > file.txt
# Windows-style CRLF endings

# Git sees this as different from LF endings:
Output
diff --git a/file.txt b/file.txt index e69de29..d95f3ad 100644 --- a/file.txt +++ b/file.txt @@ -1 +1 @@ -line1 +line1
🔧

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.

bash
# 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"
Output
Configured core.autocrlf and committed .gitattributes file. Git now normalizes line endings automatically.
🛡️

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=auto in .gitattributes for general text files.
  • Specify binary files with -text to 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.

Key Takeaways

Set core.autocrlf correctly for your operating system to handle line endings automatically.
Use a .gitattributes file to enforce consistent line endings across all contributors.
Avoid converting binary files by marking them with -text in .gitattributes.
Configure line endings before cloning to prevent conflicts later.
Check your editor settings to ensure it respects line ending conventions.