HTTP Status in Shell Script – How to Get Only the HTTP Status of a Site

croncurloutput

I figure curl would do the job. I wrote in a script:

#!/bin/sh

function test {
    res=`curl -I $1 | grep HTTP/1.1 | awk {'print $2'}`
    if [ $res -ne 200 ]
    then
        echo "Error $res on $1"
    fi
}  

test mysite.com
test google.com

The problem here is no matter what I do I can't get it to stop printing the below to stdout:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current

I want a cronjob to run this script and if it writes such a message then every time I run it I'll get an email because something has been printed to stdout in cron, even though the site may be fine.

How do I get the status code without getting junk into stdout? This code works except the bonus junk to the stdout preventing me from using it.

Best Answer

   -s/--silent
          Silent or quiet mode. Don't show progress meter 
          or error messages.  Makes Curl mute.

So your res should look like

res=`curl -s -I $1 | grep HTTP/1.1 | awk {'print $2'}`

Result is Error 301 on google.com, for example.

Related Question