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

#!/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.

我试图运行。 我没有得到一个语法错误。 事实上,它看起来大部分是很好的语法。

请看下面的输出:

 $ ./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. 

我想你想用反引号replace这一行中的引号:

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

所以把它改成:

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

这条线还有一个逻辑问题(不是语法问题),因为它将命令的stdout结果分配给result_nc。 正如戈登所build议的,将其改为:

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

并删除作业中的空格:

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

所以变成:

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

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

并检查出http://www.shellcheck.net/