10

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?

Ron
  • 6,543
  • 4
  • 23
  • 29
  • [This answer](http://stackoverflow.com/questions/2924422/how-do-i-determine-if-a-web-page-exists-with-shell-scripting) is closely related... – user000001 Aug 15 '13 at 18:11

2 Answers2

36

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.

Sithsu
  • 2,209
  • 2
  • 21
  • 28
  • 10
    +1 for including explanation of the CLI options. They're in the man file, but it's nice to have that extra level of abstraction removed with just a small amount of work on the poster's part. I wish more people would do this. – L0j1k Jan 28 '15 at 21:24
  • Is the % sign windows specific? –  Mar 28 '16 at 17:59
  • 1
    @ElgsQianChen % sign is not windows specific. Predefined variables, that are available for `-w` option of `curl`, are passed using `%{variable_name}` format. In order to run in windows, will have to manually escape % sign. From `curl` man page - `NOTE: The %-symbol is a special symbol in the win32-environment, where all occurrences of % must be doubled when using this option.` – Sithsu Apr 02 '16 at 08:58
0

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

mivk
  • 13,452
  • 5
  • 76
  • 69
praveen
  • 1
  • 1