腳本文件中出現意外的文件結束錯誤

腳本文件中出現意外的文件結束錯誤
#!/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。正如戈登建議的那樣,將其更改為:

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

並刪除作業中的空格:

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

這樣就變成:

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

因為如果有空格,作業將無法正常進行。

並檢查一下http://www.shellcheck.net/

相關內容