linux - 如何执行 url 并从 bash shell 脚本解析它?

标签 linux bash shell unix ubuntu

我正在开发一个项目,我需要从 bash shell 脚本对我的一台服务器进行 url 调用..

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

如果syncs大于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'

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

最佳答案

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

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

关于linux - 如何执行 url 并从 bash shell 脚本解析它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22235637/

相关文章:

linux - 检查预提交钩子(Hook) shell 脚本中的 git 状态

bash - 如何在 bash shell 脚本中添加整数和 float

c++ - 使用 Eclipse 调试外部控制台程序

android - 如何检查文件是否存在于 u-boot 脚本中?

c - Linux 内核 3.16 上的 Moxa RealTTY 模块编译错误

linux - 如何在没有查找的情况下在 linux shell 脚本中根据日期查找和删除文件?

bash - 命令替换不适用于 makefile 中的 echo

perl - 如何正确捕获unix命令的返回值?

linux - ubuntu 14.04 Kylin install - 无法下载metalink

linux - 通过 shell 脚本获取网站的 Url