Shell 脚本错误(:未找到 [没有那个文件或目录])

sug*_*nan 7 bash windows shell-script newlines

我在 linux 服务器上使用以下脚本。这是给:

: not found [No such file or directory]
Run Code Online (Sandbox Code Playgroud)

这是脚本:

# ------------------------------------------------------------------
# K.Sugunan Host health check
#           Description
#
#           This script to initiate health check on servers.
#           It will check for CPU, memory and some connectivity with 
#           up stream and down stream system.
#
# ------------------------------------------------------------------

# Applying initial variables and loading config parameters
DOCROOT=$(pwd)"/"
TIME_NOW=$(date +"%Y-%m-%d %H:%M:%S")

echo $DOCROOT

. $DOCROOT"config/main.sh"
. $DOCROOT"config/web.sh"
. $DOCROOT"config/telnet.sh"

echo $CPU_A
Run Code Online (Sandbox Code Playgroud)

错误将如下所示:

: not found [No such file or directory]
: not found [No such file or directory]
/home/sugunan/phobos/
: not found [No such file or directory]
: cannot open [No such file or directory]os/
Run Code Online (Sandbox Code Playgroud)

我使用以下方式运行脚本

ksh poc.sh
sh poc.sh
./poc.sh
Run Code Online (Sandbox Code Playgroud)

以上所有给出了类似的错误。即使我包括#!/bin/bash仍然存在错误。我曾尝试#!/bin/ksh#!/usr/bin/ksh也。所有这些都会导致错误。此服务器出现问题的原因可能是什么?

dr_*_*dr_ 7

看起来空行包含一个不可见(不可打印)的字符,并且服务器正在尝试运行它,就好像它是命令的名称一样;因此错误: not found [No such file or directory]。删除空行或确保它们真的是空的。

编辑:OP 的评论证实确实如此,因为代码是在 Windows 下编写的。在 Windows 上,ASCII 文本文件以换行符 + 回车符结束每一行,而 UNIX 仅使用换行符。

要解决此问题,您可以:

  • 将代码直接复制粘贴到 Linux 下的编辑器上
  • 确保您将 Windows 编辑器设置为将行尾字符转换为 UNIX 标准
  • 使用dos2unix命令将 Windows ASCII 文件转换为 UNIX 文件

  • 脚本文件包含`\r\n` 行结尾的可能性很高。 (8认同)