Get curl to output non-2xx to stderr, but 2xxs to a file

by Domenic   Last Updated August 14, 2019 14:01 PM

I would like some curl command, possibly with some bash hackery, that:

  1. Outputs any 2xx responses to a file
  2. Outputs any non-2xx responses to stderr
  3. Exits with a nonzero status code when a non-2xx response occurs

I know that the -f flag will get me 3, and that -o or pipe redirection will get me 1. But I cannot then figure out how to get 2.

Tags : bash curl


Answers 2


Could you echo the output from curl into a temp file (with the PID as part of the name). Set a timer in the background for a long time (5+ min to delete the file). Then run a sed command for #1 to a file, and then a sed command for #2 to STDerror. The second command can use the q command to return a non-zero answer. Look here for use of q command in sed. https://stackoverflow.com/questions/15965073/return-code-of-sed-for-no-match

user219861
user219861
September 01, 2015 01:03 AM

This is what I ended up doing:

HTTP_CODE=`curl http://example.com/ \
      --verbose \
      --write-out "%{http_code}" \
      --output my-output-file`

if [ "$HTTP_CODE" != "200" ]; then
    cat my-output-file
    rm my-output-file
fi
Domenic
Domenic
September 02, 2015 19:32 PM

Related Questions





how to make curl re-use existing connection

Updated August 20, 2015 21:00 PM

Delivering a payload to a URL, using cURL

Updated September 25, 2015 10:00 AM