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

Nginx 自啟動腳本報錯「env: /etc/init.d/nginx: No such file or directory」解決方案

編輯:Linux 教學

錯誤現象

service nginx status
env: /etc/init.d/nginx: No such file or directory

檔案明明存在,卻提示找不到。

根本原因

行尾換行符格式不匹配:

  • Linux/Unix:LF (\\n, 0x0A)
  • Windows:CRLF (\\r\\n, 0x0D 0x0A)

若腳本在 Windows 編輯(Notepad 等)後直接上傳到 Linux,會攜帶 \\r,導致 Shebang 行 #!/bin/bash\\r 被核心視為不存在的解譯器路徑,進而報錯。

解決方法

方法一:dos2unix 轉換(推薦)

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

# 轉換
dos2unix /etc/init.d/nginx

方法二:sed 就地替換

sed -i 's/\r$//' /etc/init.d/nginx

方法三:vim 內部轉換

vim /etc/init.d/nginx
:set fileformat=unix
:wq

方法四:tr 刪除 \\r


tr -d '\r' < /etc/init.d/nginx > /etc/init.d/nginx.new
mv /etc/init.d/nginx.new /etc/init.d/nginx
chmod +x /etc/init.d/nginx

驗證


file /etc/init.d/nginx
# 輸出應包含 "ASCII text" 或 "UTF-8 Unicode text",不含 "with CRLF line terminators"

service nginx status
# 應正常顯示狀態

預防建議

  • Linux 腳本請在 Linux 環境編輯(vim、nano、VS Code Remote SSH)。
  • Windows 編輯器設置「換行符 = LF」:Notepad++ → 編輯 → 文檔格式轉換 → Unix (LF);VS Code 右下角 CRLF → LF。
  • Git 設置 core.autocrlf=input,提交時自動轉 LF,檢出不轉 CRLF。

總結

Windows CRLF 與 Linux LF 混用是跨平台腳本部署的頭號殺手。遇到「檔案存在卻提示找不到」「語法錯誤莫名其妙」,第一時間用 dos2unix 或 sed -i 's/\\r$//' 清洗行尾,問題多半迎刃而解。

Copyright © Windows教程網 All Rights Reserved