简体   繁体   中英

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?

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.

if you're trying to store the http response to a variable.

#!bin/bash

STATUS_RECEIVED=$(curl -s --write-out "%{http_code}\n" $envUrl --output output.txt --silent) ;

echo $STATUS_RECEIVED

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM