如何执行URL并从bash shell脚本解析它?

时间:2014-03-06 20:48:57

标签: linux bash shell unix ubuntu

我正在开发一个项目,我需要从bash shell脚本中调用我的一个服务器。

http://hostname.domain.com:8080/beat

点击上面的网址后,我会得到以下回复,我需要解析它并提取syncssyncs_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

现在我需要每隔10秒钟点击上面的网址,持续10分钟,然后从中提取syncssyncs_behind的值并使用以下条件验证它 -

syncs > 8
syncs_behind = 0

如果同步大于8且syncs_behind = 0,那么我将以一些消息说“ - 数据已经过验证”结束我的shell脚本,否则我将继续尝试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'

有什么想法,我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

不是c& p准备好的解决方案,但希望能帮助您入门:

您希望将wget的输出重定向到文件中,然后使用awksed的组合来提取您实际感兴趣的部分。您将可能需要几分钟和两个命令的' hello worlds ',但值得付出努力。

在重试/退出方面,您可能需要一个带有if语句的无限循环来评估退出条件。对于时间控制,我会使用sleep命令,即使crontab可能是值得考虑的替代方案。

我建议您专注于第一部分(解析和评估),并在您准备继续前进时提出一个新问题......

答案 1 :(得分:0)

好的开始!让我们分解一下:

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