[[+content_image]]
A
A
Alexey Bely2016-11-07 16:41:16
bash
Alexey Bely, 2016-11-07 16:41:16

How to load curl or wget response into variable and compare in condition?

You need to "intercept" responses from web servers and assign your own "beautiful" error responses.
I do it like this:

request=`curl -Is -u $2:$3 $1 | head -1`
if [[ "$request" == *200* ]]
then
echo "Everything is OK!"
echo "Everything is OK!" >> ./script.log
fi

if [[ "$request" == *403* ]]
then 
echo "ERROR: Cannot connect to $1: 403"
echo "ERROR: Cannot connect to $1: 403" >> ./script.log && exit
fi

Same with wget:
request=`wget -q --user=$2 --password=$3 $1 | head -1`

That is, responses from servers are normally searched for, added to a variable, the conditions are met, my beautiful messages are obtained.
But if the site does not resolve, the response from curl or wget itself cannot be intercepted.
That is, I look at what curl really answers, I write some key phrase from there, but nothing works. In the case of wget too.
if [[ "$request" == *error* ]] # - где error это предполагаемое содержимое заголовка
then 
echo "ERROR: Cannot connect to $1: site $1 doesn't exist"
echo "ERROR: Cannot connect to $1: site $1 doesn't exist" >> ./script.log && exit
fi

What am I doing wrong?
UPD:
I tried to test the variable with ping, the same thing. Something is fundamentally wrong here, but I can't figure out what.
request1=`ping -q -c 1 $1 | /dev/null`
UPD2:
It's clear what I'm doing wrong. It was necessary to catch not the responses from the servers, but the responses of the applications themselves. It turned out to be done through this solution:
wget $1 2>/dev/null 
export RC=$? 
if [ "$RC" = "0" ]; 
then echo $1 OK 
else echo $1 FAILED 
fi

If you write it in this order so that the condition goes immediately after the command is executed, then everything works fine, the problem is solved.

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
F
frees2, 2016-11-07
@frees2

print_r
Read the header and process it however you want

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question