Exit bash script when curl gets a non 200 HTTP status

11

I have a bash script setup to perform a few curl requests

for currency in EUR INR JPY
do
  curl -i --data '{"currency": "'$currency'"}' -H "Accept: application/json" -H "Content-Type: application/json" http://0.0.0.0:8080/price && echo
done

Is there a way to make the script exit if one of the curl responses come back with an http status != 200?

I also want to keep the standard curl output, e.g I don't want a solution that only prints the http status code.

Cheers

Marklar

Posted 2015-02-12T11:32:20.530

Reputation: 334

Answers

5

--fail, as mentioned in the man page, seems to do the job:

$ curl --fail --location http://google.com/nope
$ echo $?
22

l0b0

Posted 2015-02-12T11:32:20.530

Reputation: 6 306

3From the manpage, --fail is not suitable for a couple of reasons: 1. Fail silently (no output at all), and 2. This method is not fail-safe and there are occasions where non-successful response codes will slip through. – Armand – 2016-09-12T10:38:11.737