我正在尝试编写一个脚本来查询Web服务器API并检查值,但我无法弄清楚如何最好地解决它。到目前为止,我正在做的是使用curl获取响应,然后将其传递给grep以查找模式。如果模式存在,我做一件事,如果没有,我做另一件事。
if curl http://192.168.1.2:8080/api/query | grep -q mypattern; then
echo "success"
else echo "boo"
fi
但是如果服务器关闭,我不知道如何处理这个问题,因为服务器关闭会产生与未找到模式相同的结果。我想要发生的是curl继续发出请求,直到服务器响应然后grep结果。我知道我可能会这样做,但它会非常愚蠢。一个想法是首先卷曲,直到退出代码为0,但我确信有更实用的方法。有什么想法吗?
答案 0 :(得分:0)
试试这个:
#!/bin/bash
n=5 # number of times to try.
testserver(){
read server mypattern <<<"$@" # read values of server and pattern
try=1 # lets start with try number 1.
while (( try++ < n )); do # have tried enough times?
test="$(curl --max-time 10 "$server" 2>/dev/null)"
(( $? == 0 )) && # If the connection was valid.
[[ "$test" =~ "$mypattern" ]] && echo "success" && break 1
sleep 5m # wait a little before trying again.
done
}
testserver "http://192.168.1.2:8080/api/query" "SomeStringToTest"
答案 1 :(得分:0)
这似乎不太愚蠢:
i=0; if while test $((i++)) -lt 4 && ! curl ...
您可能希望限制调用curl的时间。你可以这样做:
{{1}}
答案 2 :(得分:0)
可以使用$PIPESTATUS
:
#!/bin/bash
if curl http://192.168.1.2/api/query | grep -q mypattern; then
echo "Found pattern"
elif [ "${PIPESTATUS[0]}" -eq 0 ]; then
echo "Server up"
else
echo "Server down"
fi
答案 3 :(得分:0)
curl
具有内置超时状态,具有专用退出代码(28)。
来自文档:
--connect-timeout <seconds> Maximum time in seconds that you allow curl's connection to take. This only limits the connection phase, so if curl con- nects within the given period it will continue - if not it will exit. Since version 7.32.0, this option accepts decimal values. ..... 28 Operation timeout. The specified time-out period was reached according to the conditions.
所以你可以像这样编写主循环脚本:
#!/bin/bash
#mypattern.sh example
query="$1"
mypattern="$2"
dogrep () {
if (grep -q "$mypattern" /tmp/result);
then
echo "success"
else
echo "boo"
fi
}
curl -s --connect-timeout 5 "$query" -o /tmp/result
curlresult="$?"
case "$curlresult" in
"0") dogrep ; exit ;;
"28") echo "Could not connect to server" ; exit ;;
*) echo "something else went wrong" ; exit ;;
esac
$1
是API网址$2
是模式bash: >./mypattern.sh "http://google.com" "The document has moved"
success
bash: >./mypattern.sh "http://google.com" "The document has movde"
boo
bash: >./mypattern.sh "http://fjbdjhf" "The document has moved"
something else went wrong
bash: >./mypattern.sh "http://real.server.address.that.is.down" "The document has moved"
Could not connect to server
在上面:
如果您调整了服务器停机的条件,我相信这可以在某种程度上完善您的特定要求。
答案 4 :(得分:0)
while ! CURL_OUT="$(curl http://192.168.1.2:8080/api/query)"; do
sleep 5
done
if echo "$CURL_OUT" | grep -q mypattern ; then
echo "success"
else
echo "boo"
fi