[英]How to execute a url and parse it from bash shell script?
我正在一个项目中,需要从bash shell脚本对我的服务器之一进行url调用。
http://hostname.domain.com:8080/beat
打上面的网址后,我会得到下面的响应,我需要分析它,并提取物价值syncs
和syncs_behind
state: READY num_retries_allowed: 3 syncs: 30 syncs_behind: 100 num_rounds: 60 hour_col: 2 day_col: 0 oldest_day_col: 0
现在,我需要打上面的URL一段10分钟每10秒和提取的价值syncs
和syncs_behind
从它,使用下面的条件来验证它-
syncs > 8
syncs_behind = 0
如果同步次数大于8,并且syncs_behind = 0,那么我将在外壳脚本中显示以下消息:“数据已通过验证”,否则我将继续尝试10分钟的窗口。如果在10分钟的窗口中,不会发生这种情况,无论如何我将结束shell脚本,这意味着我不会再次尝试。
因此,我从下面的代码开始,但陷入困境,我应该怎么做才能解析来自URL的数据-
#!/bin/sh
wget -O - -q -t 1 http://hostname.domain.com:8080/beat
我对shell脚本不是很熟悉,因此在阅读它之后我才知道有关wget的知识。可能会有更好的方法来执行它。
有什么想法可以做到吗?
更新:-
我将文件保存为beat.sh
其中包含以下内容–
#!/bin/bash
COUNT=60 #number of 10 second timeouts in 10 minutes
SUM_SYNCS=0
SUM_SYNCS_BEHIND=0
while [[ $COUNT -ge "0" ]]; do
#send the request, put response in variable
DATA=$(wget -O - -q -t 1 http://hostname.domain.com:8080/beat)
#grep $DATA for syncs and syncs_behind
SYNCS=$(echo $DATA | grep -o 'syncs:: [0-9]+' | awk '{print $2}')
SYNCS_BEHIND=$(echo $DATA | grep -o 'syncs_behind: [0-9]+' | awk '{print $2}')
echo $SYNCS
echo $SYNCS_BEHIND
#add new values to the sum totals
let SUM_SYNCS+=SYNCS
let SUM_SYNCS_BEHIND+=SYNCS_BEHIND
#verify conditionals
if [[ $SYNCS -gt "8" -a $SYNCS_BEHIND -eq "0" ]]; then exit -1; fi
#decrement the counter
let COUNT-=1
#wait another 10 seconds
sleep 10
done
当我以./beat.sh
运行它时,出现以下错误-
./beat.sh: line 23: syntax error in conditional expression
./beat.sh: line 23: syntax error near `-a'
./beat.sh: line 23: `if [[ $SYNCS -gt "8" -a $SYNCS_BEHIND -eq "0" ]]; then exit -1; fi'
有什么想法我在这里做错了吗?
尚未提供C&P的解决方案,但希望可以帮助您入门:
您想将wget
的输出重定向到一个文件中,然后使用awk
和sed
的组合来提取您真正感兴趣的部分。这两个命令可能都需要几分钟和' hello worlds ',但是值得付出努力。
在重试/退出方面,您可能需要一个带有if
语句的无休止的循环,以评估退出条件。 对于时间控制,我将使用sleep
命令,即使crontab
可能是值得考虑的替代方法。
我建议着重于第一部分(分析和评估),并在您准备好继续前进时提出一个新问题...
美好的开始! 让我们分解一下:
COUNT=60 #number of 10 second timeouts in 10 minutes
SUM_SYNCS=0
SUM_SYNCS_BEHIND=0
while [[ $COUNT -ge "0" ]]; do
#send the request, put response in variable
DATA=$(wget -O - -q -t 1 http://hostname.domain.com:8080/beat)
#grep $DATA for syncs and syncs_behind
SYNCS=$(echo $DATA | grep -oE 'syncs: [0-9]+' | awk '{print $2}')
SYNCS_BEHIND=$(echo $DATA | grep -oE 'syncs_behind: [0-9]+' | awk '{print $2}')
#add new values to the sum totals
let SUM_SYNCS+=SYNCS
let SUM_SYNCS_BEHIND+=SYNCS_BEHIND
#verify conditionals
if [[ $SYNCS -gt "8" && $SYNCS_BEHIND -eq "0" ]]; then exit -1; fi
#decrement the counter
let COUNT-=1
#wait another 10 seconds
sleep 10
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.