Bash 语法错误:意外的文件结尾

Bash 语法错误:意外的文件结尾,bash,bash4,Bash,Bash4,我这里有一个小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

我这里有一个小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

以不同的方式进行

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

如果你的缩进系统化,你会发现问题:

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
通常,
端口类型
不是有效的变量名;可以。使用
$(ptype text)
运行命令
ptype text
并捕获输出,这有点令人惊讶;与
$(选项)
类似。对于变量引用,可以使用大括号:
${choice}
。代码中有一些相当明显的重复。两对“echo/read”应该在
if/else
结构之外。

使用