脚本文件中出现意外的文件结束错误

脚本文件中出现意外的文件结束错误
#!/bin/sh
#
Host = ###############
Port = ####
email_id="##################"
email_sub="######"
#
if ping -q -c 5 $Host >/dev/null
then
    result_host="Successful"
else
    result_host="Not Successful"
fi
result_nc='nc -z $Host $Port; echo $?'
if [ $result_nc != 0 ];
then
    result_port="Not Opened"
else
    result_port="Opened"
fi
mesg="Ping to host was ${result_host}, Port $port is ${result_port}."
echo "$mesg"
#echo "$mesg" | mail -s "$email_sub" $email_id

当我运行该脚本时出现错误语法错误:Unexpected end of file.

答案1

我尝试运行它。我没有收到语法错误。事实上,语法看起来基本正确。

请参阅以下输出:

$ ./a.sh
./a.sh: 3: ./a.sh: Host: not found
./a.sh: 4: ./a.sh: Port: not found
Usage: ping [-aAbBdDfhLnOqrRUvV] [-c count] [-i interval] [-I interface]
            [-m mark] [-M pmtudisc_option] [-l preload] [-p pattern] [-Q tos]
            [-s packetsize] [-S sndbuf] [-t ttl] [-T timestamp_option]
            [-w deadline] [-W timeout] [hop1 ...] destination
./a.sh: 15: [: nc: unexpected operator
Ping to host was Not Successful, Port  is Opened.

我认为您想用反引号替换此行中的引号:

result_nc='nc -z $Host $Port; echo $?'

因此将其更改为:

result_nc=`nc -z $Host $Port; echo $?`

该行还存在逻辑问题(不是语法问题),因为它将命令的标准输出结果赋值给 result_nc。根据 Gordon 的建议,将其更改为:

if nc -z $Host $Port
then
...

并删除作业中的空格:

Host = ###############
Port = ####

因此变成:

Host=###############
Port=####

因为如果有空格,作业就无法正常工作。

请检查http://www.shellcheck.net/

相关内容