Curl: Save HTTP Error in Bash to log and data to file

Viewed 168

I'm making a curl request to a REST API and now I want to save the HTTP answer code, just if an error occurs, to a logfile and the API answer to another file if there is no error occuring.

I'm trying it with:

error=$(curl -v -o "test.json" -H "Authorization: Basic ABCDEF" "https://api.abc.com")

and

error=$(curl --fail -o "test.json" -H "Authorization: Basic ABCDEF" "https://api.abc.com")

If I make an if [0 -eq $? ] after the curl request with --fail I can detect that an error occurred but I am not able to save the HTTP error to a log.

Thanks.

2 Answers

Since according man curl the option --fail

... is not fail-safe and there are occasions where non-successful response codes will slip through, especially when authentication is involved (response codes 401 and 407).

you could use --write-out and http_code.

The numerical response code that was found in the last retrieved HTTP(S) or FTP(s) transfer.

I.e.:

ERROR=$(curl --silent --fail --header "Authorization: Basic ABCDEF" "https://api.abc.com" --output "test.json" --write-out "%{http_code}")

Welcome to stackoverflow.

This should do the trick.


#send all output to file named out
curl -v -o "test.json" -H "Authorization: Basic ABCDEF" "https://api.abc.com" >out 2>&1
# find HTTP/2 code in the output
error=`grep "HTTP/2" out | tail -1 | rev | cut -c1-5 | rev`
# print the error code
echo $error

Example run:

mamuns-mac:jenkins xmrashid$ ./get_error.sh
503 
mamuns-mac:jenkins xmrashid$ 

Good Luck.

Related