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.