萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Windows/Linux 換行符差異(CRLF vs LF)導致腳本失效的根因與轉換工具

核心差異

常見故障場景

  • Shell 腳本在 Linux 執行報 /bin/bash^M: bad interpreter
  • Git 提交時警告 CRLF will be replaced by LF
  • 配置文件解析失敗(如 Nginx、MySQL cnf)
  • 跨平台文本處理工具(awk、sed)行匹配異常

一、Linux 端轉換工具

1. dos2unix / unix2dos(標準工具)

# 安裝
yum install dos2unix -y
# 或
apt-get install dos2unix

# 單文件轉換(原地修改)
dos2unix script.sh

# 批量轉換
dos2unix file1 file2 file3
dos2unix -o file1 file2   # -o 同義

# 保留時間戳
dos2unix -k script.sh

# 輸出到新文件
dos2unix -n old.sh new.sh

2. sed 就地替換

sed -i 's/\r$//' file.txt        # CRLF → LF
sed -i 's/$/\r/' file.txt        # LF → CRLF

3. tr 刪除控制字符

tr -d '\r' < win.txt > unix.txt

4. vim 設置文件格式

:set fileformat=unix
:w
# 或
:set ff=dos

二、檢測手段

# 顯示不可見字符
cat -A file.txt        # $ = LF, ^M$ = CRLF
cat -v file.txt

# 十六進制查看
hexdump -C file.txt | head -20
od -c file.txt | head -20

三、Git 端配置

# 提交時轉 LF,檢出時轉 CRLF(Windows 推薦)
git config --global core.autocrlf true

# 提交時轉 LF,檢出不轉換(Linux/Mac 推薦)
git config --global core.autocrlf input

# 禁用自動轉換,由 .gitattributes 控制
git config --global core.autocrlf false

.gitattributes 示例:

* text=auto
*.sh text eol=lf
*.bat text eol=crlf
*.png binary

四、FTP 傳輸模式

  • ASCII 模式: 自動轉換換行符(文本文件適用)
  • Binary 模式: 字節級傳輸,保持原樣(二進制、已統一格式的文本)

建議:統一倉庫為 LF,Windows 端設置 core.autocrlf=true,傳輸用 Binary 模式。

五、編輯器設置

系統換行符十六進制顯示符號
WindowsCRLF0D 0A^M$
Linux/UnixLF0A$
Mac OS 9CR0D^M

總結

換行符問題本質是「約定不一致」。團隊統一:倉庫存 LF、Windows 客戶端 autocrlf=true、編輯器默認 LF、傳輸用 Binary。遇到遺留 CRLF 文件,dos2unix -k 批量轉換即可。

copyright © 萬盛學電腦網 all rights reserved
編輯器設置 LF
VS Code右下角 CRLF → LF,或 settings.json "files.eol": "\n"
Notepad++編輯 → 文檔格式轉換 → Unix (LF)
SublimeView → Line Endings → Unix
IntelliJFile → Line Separators → LF