11

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?

1
  • This answer is closely related... Commented Aug 15, 2013 at 18:11

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+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.
Is the % sign windows specific?
@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.
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

1 Comment

why having silent twice?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.