Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

解決 Linux 執行 .sh 腳本提示「No such file or directory」:換行符格式轉換三法

編輯:Linux 教學

在 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 解譯器而失敗。

方法一:Windows 端預先轉換(推薦)

使用支援換行符轉換的編輯器:

  • UltraEdit:File → Conversions → DOS → UNIX
  • EditPlus:文件 → 轉換換行符 → UNIX
  • Notepad++:編輯 → 文檔格式轉換 → 轉為 UNIX 格式
  • VS Code:右下角 CRLF 點擊切換為 LF。

轉換後存檔再上傳 Linux,直接可執行。

方法二:Linux 端用 Vim 即時轉換

vim script.sh
# 在命令模式輸入:
:set ff=unix
:wq

驗證::set ff 顯示 fileformat=unix 即成功。

方法三:Linux 指令列工具批次轉換

# sed 就地替換
sed -i 's/\r$//' script.sh

# 或使用 dos2unix(需安裝)
yum -y install dos2unix
dos2unix script.sh

前置條件:確保執行權限

無論哪種方法,執行前需賦予執行權限:

chmod +x script.sh

總結建議

  • 習慣在 Windows 用 VS Code/Notepad++ 直接存為 LF 格式,源頭杜絕問題。
  • Git 設定 core.autocrlf=input 可自動簽入時轉 LF。
  • 批次處理大量腳本用 find . -name "*.sh" -exec dos2unix {} \;。
Copyright © Windows教程網 All Rights Reserved