使用If-Else语句检查Bash脚本的输出

使用If-Else语句检查Bash脚本的输出,bash,Bash,我希望bash脚本运行以下命令 iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000 如果没有使用找到它的输出 iptables -t nat --list 如何使用If-Else查找输出。我可以使用“cat”吗?使用$()捕获命令的输出,并使用-z确定命令是否为空: output=$(iptables -t nat --list) if [ -z $output ] #

我希望bash脚本运行以下命令

iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000
如果没有使用找到它的输出

iptables -t nat --list
如何使用If-Else查找输出。我可以使用“cat”吗?

使用
$()
捕获命令的输出,并使用
-z
确定命令是否为空:

output=$(iptables -t nat --list)
if [ -z $output ] # returns true if the length of $output is 0
then
    output=$(iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000)
fi
使用
$()
捕获命令的输出,并使用
-z
确定命令是否为空:

output=$(iptables -t nat --list)
if [ -z $output ] # returns true if the length of $output is 0
then
    output=$(iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000)
fi

您可以将grep与iptables列表一起使用,这取决于您试图匹配它的方式

if iptables -t nat --list PREROUTING | grep -- '--destintation-port 80' | grep -q -- '--to-port 10000'
    iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000
fi

这将查看是否有一个预路由条目同时涉及到目标端口80和到端口10000。如果输出字符串更可预测,则可以使用单个grep,但我对iptables了解不够,无法将其作为解决方案的一部分提供

您可以将grep与iptables列表一起使用,具体取决于您尝试如何匹配它

if iptables -t nat --list PREROUTING | grep -- '--destintation-port 80' | grep -q -- '--to-port 10000'
    iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000
fi

这将查看是否有一个预路由条目同时涉及到目标端口80和到端口10000。如果输出字符串更可预测,您可以使用单个grep,但我对iptables了解不够,无法将其作为解决方案的一部分提供

我不认为他们只是希望
iptables-t nat--list
为空,因为它几乎永远不会为空,因为如果没有其他内容,它会打印标题。我认为他们想检查路由规则是否已经存在,这将是他们表达式中的“of it”—当然我不能确定这是他们想要的mean@EricRenouf我不知道,谢谢你的提醒。在这种情况下,我会投票支持你的答案。我不认为他们只是希望
iptables-tnat--list
为空,因为它只打印标题,而不打印其他内容。我认为他们想检查路由规则是否已经存在,这将是他们表达式中的“of it”—当然我不能确定这是他们想要的mean@EricRenouf我不知道,谢谢你的提醒。如果是那样的话,我就投你的赞成票。