Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch timeout/errors in a CURL shell script?

I want to issue a cURL GET request to a URL and based on the return HTTP code decide whether to do something with the returned HTTP data.

For example, if the HTTP code for a certain url request through cURL is valid (not timed out or error), then keep the returned data from the request somewhere in my system.

How can I actually 'catch' the returned HTTP code (or timeout) and do the decision based on that?

like image 727
Ron Avatar asked Aug 15 '13 18:08

Ron


1 Answers

Execute following as script.sh http://www.google.com/.
-D - dump headers to file
-o - write response to file
-s - be silent
-w - display value of specified variables

#!/bin/bash

RESPONSE=response.txt
HEADERS=headers.txt

status=$(curl -s -w %{http_code} $1 -o $RESPONSE)

# or
#curl -s -D $HEADERS $1 -o $RESPONSE
#status=$(cat $HEADERS | head -n 1 | awk '{print $2}')

echo $status

Use $status and $RESPONSE for further processing.

like image 130
Sithsu Avatar answered Sep 28 '22 01:09

Sithsu