【问题标题】:syntax error: unexpected end of file语法错误:文件意外结束
【发布时间】:2014-12-19 05:59:32
【问题描述】:

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

【问题讨论】:

标签: bash bash4


【解决方案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

【讨论】:

    【解决方案2】:

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

    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 结构之外。

    【讨论】:

      猜你喜欢
      • 2011-09-16
      • 2017-06-08
      • 2013-04-13
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多