curl流输出逐行读取并包含条件

50few1ms  于 2022-12-27  发布在  其他
关注(0)|答案(3)|浏览(175)

我有一个API网址,允许监视一些事件。我能够用一个简单的代码curl "https://theurl.events/logs"所有的日志都是文本格式,它永远不会结束,所以我只是运行curl命令,让它在那里。
现在,我想设置一些条件,如果日志包含keyword,则执行一些操作。
日志如下所示,它看起来像json,但它是文本而不是json

action=machinestarted,
data={
    "location": "Place A"
    "lag": "033"
    "size": "5543"
    "id": "11",
    .....
}
action=Error,
data={
    "location": "Place B"
    "lag": "033"
    "size": "5543"
    "id": "11",
    .....
}

到目前为止,我可以通过curl "https://theurl.events/logs" 2>&1 | grep Error | ./runbash.sh过滤日志
由于事件的增长,我想grep更多的关键字,如grep WrongOperationgrep WrongButton,然后我想运行不同的bash文件。
我不认为把它们分开运行是个好主意

"https://theurl.events/logs" 2>&1 | grep Error` | ./runbash1.sh
"https://theurl.events/logs" 2>&1 | grep WrongOperation` | ./runbash2.sh
"https://theurl.events/logs" 2>&1 | grep WrongButton` | ./runbash3.sh

所以我想知道是否可以使用while循环curl的输出并包含多个条件,例如

while IFS= read -r line (from curl)
do
  if [[ "$line" == *"WrongOperation"* ]]; then
    //do something
   elif
    [[ "$line" == *"WrongButton"* ]]
    //.....
done
kx7yvsdv

kx7yvsdv1#

如果没有while + read循环,就像这样。

#!/usr/bin/env bash

output=$(
  curl "https://theurl.events/logs" 2>&1 |
  grep -E 'Error|WrongOperation|WronButton' 
)

printf '%s\n' "$output"

if [[ $output =~ Error ]]; then
  echo ./runbash1.sh
elif [[ $output =~ WrongOperation ]]; then
  echo ./runbash2.sh
elif [[ $output =~ WronButton ]]; then
  echo ./runbash3.sh
fi

如果您对输出满意,请删除echo

vc9ivgsu

vc9ivgsu2#

您可以依赖以下方法:

while IFS= read -r line
do
  if [[ "$line" == *"WrongOperation"* ]]; then
    //do something
   elif
    [[ "$line" == *"WrongButton"* ]]
    //.....
done < $(YOUR_CURL_COMMAND_LINE)

YOUR_CURL_COMMAND_LINE替换为curl命令。
做那件事。
问候。

sshcrbum

sshcrbum3#

请考虑以下方法:

#!/bin/bash

events=(
    # Event type   |  Action
    'error          ./runbash1.sh'
    'wrongoperation ./runbash2.sh'
    'wrongbutton    ./runbash3.sh'
)

data=$(curl "https://theurl.events/logs")

for event in "${events[@]}"; do
    read     type action <<<  $event
    grep -i $type        <<< "$data" && $action
done

不使用grep:

[[ $data =~ $type ]] && $action

相关问题