linux - 在 bash 脚本中将一个 IF 内的各种条件分组

标签 linux bash firewall iptables

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

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

最佳答案

假设 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 中具有相同的优先级;请注意每次结束前的分号 } 是必需的。

关于linux - 在 bash 脚本中将一个 IF 内的各种条件分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54868845/

相关文章:

linux - 无法将浮点值传递给 GLSL?

bash - xmllint 解析 html 文件

.net - 为什么 C# Google.Cloud.Firestore 库无法连接到企业 MITM 防火墙?

centos - 在 CentOS 中永久禁用 iptables

c++ - 执行一个故意在另一个程序中崩溃的程序,然后返回到原始进程

linux - 如何在 linux 上识别重命名的文件?

linux - 在基于 GCP 的 Ubuntu 实例中安装 Nexus

bash - 使用 ssh 的 TRAMP 不获取 .bash_profile/.profile

bash - 您可以将参数传递到 Cloudformation 中的 bash 脚本中吗?

google-app-engine - 将托管在谷歌应用引擎中的应用程序列入白名单