我有一個API網址,可以監控一些事件。我可以通過一個簡單的代碼來做到這一點 curl "https://theurl.events/logs" 所有的日志都是文本格式的,它永遠不會結束,所以我只是運行curl命令并把它留在那里。
現在我想設定一些條件,如果日志包含一個關鍵字,那么就做一些事情。
日志看起來像下面這樣,它看起來像json,但它是文本而不是json
action=machinestarted,
data={
"location": "地點A": "地點".
"滯后"。"033": "033""size": "5543": "5543""id": "11",
.....
}
action=Error,
data={
"location": "地點B": "地點B""滯后"。"033": "033""size": "5543": "5543"
"id": "11",
.....
}
到目前為止,我可以用curl "https://theurl.events/logs" 2>&1 | grep Error | ./runbash.sh
由于事件越來越多,我想搜索更多的關鍵詞,例如:grep WrongOperation, grep 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"/span>* ]]; then
//do something
elif
[[ "$line" == *"RongButton"* ]]
//.....
done>
uj5u.com熱心網友回復:
沒有while read回圈,就像這樣。
#!/usr/bin/env bash
output=$(
curl "https://theurl.events/logs" !
grep -E 'Error|WrongOperation|WronButton' 2>& 1
)
printf '%s
' "$output"
if [[ $output =~ Error ]]; then
echo ./runbash1.sh
elif [[ $output =~ WrongOperation ]]; then
echo ./runbash2.sh
elif [[ $output =~ WronButton ]]; then
echo ./runbash3.sh
fi
如果你對輸出結果滿意的話,就去掉echo的內容。
uj5u.com熱心網友回復:
你可以依靠以下方法:
while IFS= read -r line
do -r line
if [[ "$line" == *"WrongOperation"/span>* ]]; then
//do something
elif
[[ "$line" == *"RongButton"* ]]
//.....
done < $(YOUR_CURL_COMMAND_LINE)
將YOUR_CURL_COMMAND_LINE替換為你的curl命令。
謝謝你。
uj5u.com熱心網友回復:
考慮一下這個方法:
#!/bin/bash
事件=(
#事件型別|動作
'error ./runbash1.sh'
'錯誤操作 ./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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/319787.html
標籤:
