bash - shell中的嵌套逻辑表达式测试

标签 bash shell

我正在尝试编写一行代码来替代下面的代码片段。

# Check to see if the database is online; exit if not
isbooted=`grep 'Current state: Booted' serverlog.log | wc -l`
if [ $isbooted -eq 0 ]
then
   exit 
fi 

# Check to see if the database has crashed; exit if so
iscrashed=`grep 'Status: OK' serverlog.log | wc -l`
if [ $iscrashed -eq 0 ]
then 
   exit 
fi

echo 0

这是我到目前为止所做的(我不确定这是否正确),

   [ $(grep 'Current state: Booted' serverlog.log | wc -l) -eq 0 ] \
&& [ $(grep 'Status: OK' serverlog.log | wc -l) -eq 0 ]            \
&& echo 0

你能帮我一下吗?

最佳答案

这个想法似乎不错,但我会选择简化版本:

grep -q 'Current state: Booted' serverlog.log && grep -q 'Status: OK' serverlog.log && echo 0

或者(如果您希望这两行只出现一次,您可以将 -ge 替换为 -eq):

[ "$(grep -c -e 'Current state: Booted' -e 'Status: OK' serverlog.log)" -ge 2 ] && echo 0

如果serverlog.log同时包含“当前状态:已启动”状态:正常,则两个版本都打印 0。

更多引用请参见grep(1) .

关于bash - shell中的嵌套逻辑表达式测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48077537/

相关文章:

c - 在 C 中传递两个 shell 命令

linux - 是否有用于在 bash 后台启动进程的 linux util?

linux - 已解决 : PAM module bash script on sudo breaks Zenity -/bin/bash failed: exit code 126 -/bin/bash failed: exit code 126

bash - 在bash输出中去除字符

windows - Windows 中文件夹的 Shell 快捷方式

C Bash Shell 重定向

bash - 在 "trap EXIT"中获取 shell 脚本的退出代码

bash - 如何从具有制表符分隔列的文件中提取第一列

linux - 删除 awk printf/print 之间的空格分隔符

java - 通过 shell 脚本启动的重复进程