【问题标题】:Scope inside a heredoc in bash, my $PORT variable is not workingbash 中的 heredoc 内的范围,我的 $PORT 变量不起作用
【发布时间】:2019-02-16 12:15:00
【问题描述】:

我在网上找不到任何关于此的信息,但我发现我不应该在 EOT 上使用引号,但就我而言,如果有人可以在这里帮助我,那将是很棒的。 .........

这是设置新的Debian 安装脚本的一部分

问题: cat/EOT here-document 运行时,我无法访问 $PORT。

setUPiptables()
{

    if ! grep -e '-A INPUT -p tcp --dport 80 -j ACCEPT' /etc/iptables.up.rules
    then
        cat << EOT >> /etc/iptables.test.rules
        *filter


        IPTABLES-CODE-HERE

        # Allows SSH connections
        # The --dport number is the same as in /etc/ssh/sshd_config
        -A INPUT -p tcp -m state --state NEW --dport $PORT -j ACCEPT


        IPTABLES-CODE-HERE

        COMMIT
EOT
        sleep 5
        /sbin/iptables-restore < /etc/iptables.test.rules || exit 127
        sleep 5
        /sbin/iptables-save > /etc/iptables.up.rules || exit 127
        sleep 3
        printf "#!/bin/bash\n/sbin/iptables-restore < /etc/iptables.up.rules" > /etc/network/if-pre-up.d/iptables
        chmod +x /etc/network/if-pre-up.d/iptables
        sleep 6
    fi
}

问题:

您能在cat iptables 代码中找到/看到$PORT 的问题吗?

【问题讨论】:

    标签: bash shell heredoc


    【解决方案1】:

    尝试使用,因为这是question的重复答案:

    cat &lt;&lt;'EOT' &gt;&gt; /etc/iptables.test.rules

    【讨论】:

    • 嗯?这根本不是取消引用变量,而是将 literal 文本 $PORT 放入 heredoc。如果 OP 希望他们的heredoc 不是而是文字,更好的方法是将&lt;&lt;EOF 更改为&lt;&lt;'EOF'
    • @CharlesDuffy 我遇到了同样的问题,对我来说这很有效。
    • 我不相信你所拥有的确实是同样的问题。 OP 正在运行read -r port; PORT=$port 他们生成heredoc,所以他们希望他们从用户那里读取的值——而不是变量引用——进入heredoc。
    • 如果 OP 想要取消引用它,相比之下,他们的问题是重复的(我们在知识库中已经有很多条目)。参见例如How to cat <<EOF >> a file containing code?How to suppress variable substitution in bash heredocs 等。
    • ...请注意关于“之前已经被多次询问和回答过”的问题的要点,在 @ 的“回答好问题”部分987654324@.
    【解决方案2】:

    我很抱歉在这个问题上花费了人们的时间,这是一个初学者的错误,我正在阅读 grep 中的文件名而不是实际的 file(/etc/iptables.test.rules),所以我连接了 HERE-DOC 多个在iptables-save 尝试与 $PORT duplicates 一起使用的实际文件中的时间,当然它会因所有额外的代码(乱码)而失败。

    问题解决了......来自冰岛的抱歉。

    所以我没有创建/编码检查是否设置了 iptables 并且文件 /etc/iptables.test.rules 存在,所以我将双 iptables 代码附加到已经包含我正在编写的代码的文件中。

    感谢@CharlesDuffy 的时间和建议/指导

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-12
      相关资源
      最近更新 更多