【发布时间】:2014-03-06 20:48:57
【问题描述】:
我正在做一个项目,我需要从 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
现在我需要在 10 分钟内每 10 秒点击一次上述 url,并从中提取 syncs 和 syncs_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'
任何想法我在这里做错了什么?
【问题讨论】:
-
关闭了那个,因为我不确定哪个网站适合这类问题。
标签: linux bash shell unix ubuntu