在 Windows 編輯的 Shell 腳本上傳到 Linux 執行時,常因換行符差異(Windows CRLF vs Linux LF)導致 bash: ./script.sh: /bin/bash^M: bad interpreter: No such file or directory。本文提供三種快速修正方法。
腳本首行 #!/bin/bash 後隱藏 ^M(CR),導致核心嘗試尋找 /bin/bash^M 解譯器而失敗。
使用支援換行符轉換的編輯器:
File → Conversions → DOS → UNIX文件 → 轉換換行符 → UNIX編輯 → 文檔格式轉換 → 轉為 UNIX 格式轉換後存檔再上傳 Linux,直接可執行。
vim script.sh
# 在命令模式輸入:
:set ff=unix
:wq
驗證::set ff 顯示 fileformat=unix 即成功。
# sed 就地替換
sed -i 's/\r$//' script.sh
# 或使用 dos2unix(需安裝)
yum -y install dos2unix
dos2unix script.sh
無論哪種方法,執行前需賦予執行權限:
chmod +x script.sh
core.autocrlf=input 可自動簽入時轉 LF。find . -name "*.sh" -exec dos2unix {} \;。