4

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.

5
  • Shot in the dark, but it looks like a combination of --output, --silent, and --show-errors might do the trick? Commented Sep 1, 2015 at 0:35
  • Thanks; I tried that and it seems like --output always wins :(
    – Domenic
    Commented Sep 1, 2015 at 0:46
  • Are you sure? curl -fsS -o filename http://example.com/ works. Commented Sep 1, 2015 at 3:46
  • (confirmed using curl 7.43.0) Commented Sep 1, 2015 at 3:53
  • @200_success I just tried that and it gave me "curl: (22) The Requested URL returned error: 500 Internal Server Error" instead of the actual response body.
    – Domenic
    Commented Sep 2, 2015 at 19:07

2 Answers 2

1

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

1

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .