使用`stdin`在附加行上测试`test`

时间:2016-05-26 06:32:51

标签: bash

CSV日志文件每10秒追加一行,格式为:“dateintintint”。

我正在寻找一种方法来运行此文件上的脚本(或单个命令),以便在其中一个int低于定义值时发出警报。

到目前为止,我想使用int使用一个tail -f logfile | cut -d "," -f 2进行测试,但我不知道如何将stdintest一起使用。

任何建议,即使不使用tail,也是受欢迎的。警报上升可以是echo,可以测试。

3 个答案:

答案 0 :(得分:3)

这里有一些假设,但这可能接近你的预期结果:

tail -f logfile |awk -F\, -v limit=5 '$2<limit{print "alert"}'

当然,您的limit var应根据您的需要进行设置,{print "alert"}可以替换为任何操作。

处理多个列:

tail -f market.log |awk -F\, -v limit=800 '$2<limit{print "alert 1"}$3<limit{print "alert 2"}'

答案 1 :(得分:2)

klashxx's helpful awk-based answer有效,但是为了响应低于阈值的值而调用shell命令有点尴尬(你可以使用system()中的awk函数。)

这是一个解决这个问题的解决方案,通过使用带有read的Bash循环来解析每一行,这样可以很容易地调用任意shell命令来响应警报:

#!/usr/bin/env bash

limit=800  # define threshold value
while IFS=, read dt i1 i2 i3; do
  if (( i1 < limit )); then
    echo "i1 below limit"  # invoke any shell command here
  elif (( i2 < limit )); then
    echo "i2 below limit"
  elif (( i3 < limit )); then
    echo "i3 below limit"
  else
    echo "OK"
  fi
done < <(tail -n 1 -f logfile)

如果您愿意(虽然我不推荐它),您可以将其填充到单行中,可选择使用管道:

tail -n 1 -f logfile | { limit=800; while IFS=, read dt i1 i2 i3; do if (( i1 < limit )); then echo "i1 below limit"; elif (( i2 < limit )); then echo "i2 below limit"; elif (( i3 < limit )); then echo "i3 below limit"; else echo "OK"; fi done; }

答案 2 :(得分:0)

这可以是完整的脚本:

#!/bin/bash 
while true
do
  awk -v threshold=$1 'BEGIN{
  FS=","
  }
  END{ 
  # threshold value passed as arg1 is stored in awk variable threshold                 
  if( $2 < threshold){ #checking if value goes below threshold
    print "Beep Beep"
  }
  }' /path/to/your/csv_file
  sleep 10s # Remember CSV log file is appended every 10 seconds
done

将脚本保存为,例如,threshold_checker和 像

一样运行它
threshold_checker threshold_value
相关问题