I need a Linux command to launch an HTTP request, and:

  • dump the HTTP response (content, not headers) on the terminal standard output
  • return an command error status of 0 if the request went well (ended up with HTTP code 200 OK), and non-zero in all other cases (404, 500, connection failed, etc)

Gratis, needs to work on most Linux distributions, bonus for Mac.

curl does not seem to be able to do that, as its --fail switch prevents HTTP output.

  • Raw idea: a simple Bash wrapper. Capture output into a file, check for HTTP status, then act accordingly (cat the file and rc=0, or simply rc>0 otherwise)?
    – Izzy
    Mar 7 '17 at 10:54
  • 1
    @Izzy: Thanks, done :-)
    – Nicolas Raoul
    Mar 8 '17 at 7:10
  • Upvoted. Just don't forget to delete your $HEADERS when done, or after a while you've got plenty of temp files :)
    – Izzy
    Mar 8 '17 at 7:55
  • Anytime! I've solved a lot of similar issues this way – a few lines Bash can do a lot. And if it's a one-liner, it often ends up as alias :)
    – Izzy
    Mar 8 '17 at 8:04

This small bash wrapper does the trick:

# Perform a web request, dump content, and exit with relevant exit code

# Take URL as command-line argument

# Launch HTTP request
curl --dump-header $HEADERS $URL

# Read the first header (example: HTTP/1.1 200 OK)
HEADER=`head -n 1 $HEADERS`

# Remove temporary file

# Return success if HTTP code OK, or failure for any other HTTP code
if [[ $HEADER == *" 200 "* ]]; then
  exit 0
  exit 1

It requires curl and bash.

License: Public domain

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.