2014-12-19 68 views
0

我在這裏有一個小bash腳本我試圖解決,但我不斷收到一個語法錯誤,指出「意外的文件結束」。它詢問我是否想阻止或取消阻止,並詢問哪種類型的端口然後出錯。語法錯誤:意外的文件結尾

任何幫助將不勝感激。

#!/bin/bash 

PTYPET="What kind of port? [udp] or [tcp] or [both] :" 
PTEXTT="What port? [number] :" 

echo "Would you like to block or unblock? [b] or [u] :" 
read choice 

if [ $(choice) == "u" ]; then 
    echo $PTYPET 
    read port-type 
    echo $PTEXTT 
    read port 
    if [ $(ptype-text) == "both" ]; then 
     /sbin/iptables -A INPUT -p $port-type -m tcp --dport $port -j ACCEPT 
     /sbin/iptables -A INPUT -p $port-type -m udp --dport $port -j ACCEPT 
    else 
    /sbin/iptables -A INPUT -p $port-type -m $port-type --dport $port -j ACCEPT 
fi 

else 
    echo $PTYPET 
    read port-type 
    echo $PTEXTT 
    read port 
    if [ $(ptype-text) == "both" ]; then 
     /sbin/iptables -A INPUT -p $port-type -m tcp --dport $port -j DROP 
     /sbin/iptables -A INPUT -p $port-type -m udp --dport $port -j DROP 
    else 
    /sbin/iptables -A INPUT -p $port-type -m $port-type --dport $port -j DROP 
fi 
+3

使用http://www.shellcheck.net/ – Cyrus 2014-12-19 06:03:37

回答

1

以一種不同的方式去了。

#!/bin/bash 

echo "Would you like to block or unblock? [ACCEPT] or [DROP] :" 
    read choice 
echo "What kind of port? [udp] or [tcp] or [both] :" 
    read porttype 
echo "What port? [number] :" 
    read port 

    if [[ $porttype == "both" ]]; then 
     /sbin/iptables -A INPUT -p tcp -m tcp --dport $port -j $choice 
     /sbin/iptables -A INPUT -p udp -m udp --dport $port -j $choice 
    else 
    /sbin/iptables -A INPUT -p $porttype -m $porttype --dport $port -j $choice 
fi 
1

如果你在你的縮進系統,你會發現這個問題:

if [ $(choice) == "u" ]; then 
    echo $PTYPET 
    read port-type 
    echo $PTEXTT 
    read port 
    if [ $(ptype-text) == "both" ]; then 
     /sbin/iptables -A INPUT -p $port-type -m tcp --dport $port -j ACCEPT 
     /sbin/iptables -A INPUT -p $port-type -m udp --dport $port -j ACCEPT 
    else # Indent next two lines 
     /sbin/iptables -A INPUT -p $port-type -m $port-type --dport $port -j ACCEPT 
    fi 
else 
    echo $PTYPET 
    read port-type 
    echo $PTEXTT 
    read port 
    if [ $(ptype-text) == "both" ]; then 
     /sbin/iptables -A INPUT -p $port-type -m tcp --dport $port -j DROP 
     /sbin/iptables -A INPUT -p $port-type -m udp --dport $port -j DROP 
    else # Indent the next two lines 
     /sbin/iptables -A INPUT -p $port-type -m $port-type --dport $port -j DROP 
    fi 
# And now it is clear that this fi was missing! 
fi 

經典,port-type是不是一個有效的變量名;下劃線是可以的。使用$(ptype-text)正在運行命令ptype-text並捕獲輸出,這有點令人驚訝;與$(choice)類似。對於變量引用,請使用大括號:${choice}。代碼中有一些相當明顯的重複。這兩對'echo/read'應該在if/else結構之外。

相關問題