【问题标题】:Group various conditions inside one IF in a bash script在 bash 脚本中对一个 IF 内的各种条件进行分组
【发布时间】:2019-02-25 14:52:40
【问题描述】:

我正在尝试对这些条件进行分组,但它正在返回:

awaited conditional binary operator
waiting for `)'
syntax error next to `$thetime'
`  ( dateutils.dtest $thetime --gt '09:30:00' && dateutils.dtest $thetime --lt '11:00:00' ) ||'

我已经尝试过:

https://unix.stackexchange.com/questions/290146/multiple-logical-operators-a-b-c-and-syntax-error-near-unexpected-t

Groups of compound conditions in Bash test

#!/bin/bash

thetime=$(date +%H:%M:%S)

if [[
  ( dateutils.dtest $thetime --gt '09:30:00' && dateutils.dtest $thetime --lt '11:00:00' ) ||
  ( dateutils.dtest $thetime --gt '13:00:00' && dateutils.dtest $thetime --lt '17:00:00' )
]]; then
  iptables -A OUTPUT -d 31.13.85.36 -j REJECT
else
  iptables -A OUTPUT -d 31.13.85.36 -j ACCEPT
fi

【问题讨论】:

  • --gt 不是bash 运算符;无论dateutils.dtest 是什么都支持它吗?
  • 是的,它来自 dateutils.dtest 参数

标签: linux bash firewall iptables


【解决方案1】:

假设dateutils.dtest 只是一个普通的可执行文件,它使用它的参数来执行某种比较,你想要类似的东西

if { dateutils.dtest $thetime --gt '09:30:00' &&
     dateutils.dtest $thetime --lt '11:00:00'; } ||
   { dateutils.dtest $thetime --gt '13:00:00' &&
     dateutils.dtest $thetime --lt '17:00:00'; }; then
  iptables -A OUTPUT -d 31.13.85.36 -j REJECT
else
  iptables -A OUTPUT -d 31.13.85.36 -j ACCEPT
fi

这假设,例如,如果$thetime 在 9:30:00 之后,dateutils.dtest 的退出状态为 0,否则退出状态为非零。

大括号 ({ ... }) 充当分组运算符,因为 &&|| 在 shell 中具有相同的优先级;注意每个结束前的分号 } 是必需的。

【讨论】:

  • 另一个答案尝试将dateutils.dtest 的输出作为附加命令执行(除非它们不产生输出,在这种情况下不需要命令替换)。
【解决方案2】:

您可以执行以下操作:

#!/bin/bash

thetime=$(date +%H:%M:%S)

if ( $(dateutils.dtest $thetime --gt '09:30:00') && $(dateutils.dtest $thetime --lt '11:00:00') ) || ( $( dateutils.dtest $thetime --gt '13:00:00' ) && $( dateutils.dtest $thetime --lt '17:00:00' ) ); then
  iptables -A OUTPUT -d 31.13.85.36 -j REJECT
else
  iptables -A OUTPUT -d 31.13.85.36 -j ACCEPT
fi

【讨论】:

  • @MarcoA.Braghim 您期待来自dateutils.dtest 的输出吗?
【解决方案3】:

我会丢掉冒号 (:) 并进行以下比较:

thetime=$(date +%H%M%S)

if [ "$thetime" -gt "093000" ] && [ "$thetime" -lt "110000" ] || [ "$thetime" -gt "130000" ] && [ "$thetime" -lt "170000" ]; then
  iptables -A OUTPUT -d 31.13.85.36 -j REJECT
else
  iptables -A OUTPUT -d 31.13.85.36 -j ACCEPT
fi

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 2014-12-16
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    相关资源
    最近更新 更多