1

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.

3
  • 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, 2017 at 10:54
  • 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, 2017 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, 2017 at 8:04

1 Answer 1

1

This small bash wrapper does the trick:

#!/bin/bash
# Perform a web request, dump content, and exit with relevant exit code

# Take URL as command-line argument
URL=$1

# Launch HTTP request
HEADERS=`mktemp`
curl --dump-header $HEADERS $URL

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

# Remove temporary file
rm $HEADERS

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

It requires curl and bash.

License: Public domain

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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