Git commit.template中出现^M特殊字符的去除方法咨询
Hey, I’ve dealt with this annoying ^M issue plenty of times—those are just Windows-style carriage return (CR) characters clashing with Unix/macOS line endings (LF). Here’s how to get rid of them for good:
First, confirm the problem
Run this command to see the raw line endings in your commit template (replace the path with your actual template file location):cat -A ~/.gitcommit.template
You’ll see those ^M characters show up as\rat the end of lines, which confirms it’s a line ending mismatch.Convert the template file to Unix-style line endings
Pick one of these quick methods:- Use
dos2unix(simplest if available):dos2unix ~/.gitcommit.template
This tool directly converts CRLF to LF in place. - Use
sedif you don’t havedos2unix:sed -i 's/\r$//' ~/.gitcommit.template
This command strips out the trailing\rfrom every line. - Use Vim:
Open the file withvim ~/.gitcommit.template, then in command mode type:set fileformat=unixand save with:wq. This rewrites the file with Unix line endings.
- Use
Prevent this from happening again
Set Git to handle line endings automatically so future edits don’t reintroduce the issue:git config --global core.autocrlf input
This tells Git to convert any CRLF line endings to LF when you commit files, while leaving your working directory files as-is (ideal for Unix/macOS). If you’re on Windows, usegit config --global core.autocrlf trueinstead.
The root cause here is that your commit template file was probably created or edited on a Windows system, which uses CRLF (\r\n) line endings, while your current system expects just LF (\n). Converting the file and setting up Git’s line ending handling will make those ^M characters disappear for good.
内容的提问来源于stack exchange,提问作者Marfaldo

