I am trying to write a script to query a web server API and check for a value but I am having trouble trying to figure out how to best go about it. So far what I am doing is using curl to get a response and then piping that to grep to look for a pattern. If the pattern exist, I do one thing, if not, I do another.
if curl http://192.168.1.2:8080/api/query | grep -q mypattern; then
echo "success"
else echo "boo"
fi
But if the server is down I don't know how to handle that neatly because the server being down produces the same result as not finding the pattern. What I want to happen is for curl to keep making the request until the server responds and then grep the result. I know I could probably do it but it will be very kludgy. One thought was a loop to curl first until the exit code is 0 but I'm sure there is a more practical way. Any ideas?
One can use $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