Recursively convert line endings dos2unix / mac2unix
To recursively convert line endings from DOS \r\n and old macOS \r to Unix \n format use
dos2unix
and mac2unix commands.
Source code files shared among groups might end up with DOS line endings, which can cause issues across different operating systems.
When viewed with “git diff” or similar, files might have ^M characters at the end of lines, indicating DOS or old macOS line endings.
It’s important not to blindly use dos2unix or other mass conversion utilities on a recursive subtree, as the .git/ directory files could be corrupted.
Install dos2unix and mac2unix
dos2unix and mac2unix are available to install by package manager:
- macOS:
brew install dos2unix - Linux:
apt install dos2unixor similar package manager command - Windows:
winget install --id=waterlan.dos2unix -e
Recursive conversion of Git-tracked files line endings
xargs
manages running a command across numerous files in parallel from stdin.
xargs is built into most Unix-like systems, including macOS and Linux, so no additional installation is typically required.
For Windows, obtain xargs via the Microsoft Coreutils package: winget install --id=Microsoft.Coreutils -e
git ls-files -z | xargs -0 dos2unix --add-eol-z- separate paths with the NUL character (
\0) for consumption byxargs -0
Set Git to use the correct line endings to avoid line ending conflicts in Git repositories.
For the less common case of needing to convert from old macOS \r line endings to Unix \n line endings, use mac2unix similarly.
dos2unix and mac2unix are each idempotent, so it doesn’t hurt to run them in any order.
git ls-files -z | xargs -0 mac2unix --add-eolNon Git-tracked files
For non Git-tracked files, use findutils “find” to recursively convert line endings:
find . -not \( -path "./.git" -type d -prune \) -type f -exec dos2unix --add-eol {} + -exec mac2unix --add-eol {} +