Check status code from a URL in Bash

Bash Script

Bash Status Code

The following script is for my own reference. It’s a simple script that pings a URL and looks for a bash status code of 200. If the response does not return the status code of 200, it will add an entry to a log file. Inside that block of code you can do further actions, such as send an SMS alert.

#!/bin/bash

url="www.mywebsite.com"
status_code=$(curl -o /dev/null --silent --head --write-out '%{http_code}\n' $url)
date=`date`

if [ $status_code -ne "200" ]
then
        echo "status check failed at $date" >> /var/log/status_check.log
        #You can add further actions here
fi

SMS Alerts

Since I mentioned SMS alerts, I might as well cover the basics of sending SMS here. One way to do it is to get API access to one of the SMS gateways. The easiest and the quickest SMS api in my opinion is SMSify. If you get an SMSify account, you will automatically get access to their developer API. All you need to do is purchase SMS credits, which are dead cheap. Let’s say you’ve got an SMSify account and they API key. You can then write a simple Ruby script that sends SMS to any mobile number. First you will need to download SMSify ruby gem:

gem install smsify

Now you are ready to send SMS using our ruby wrapper like this:

#!/usr/bin/env ruby

require 'rubygems'
require 'smsify'
 
smsify = SMSify.new("your_smsify_api_key")
response = smsify.sendSMS("Your SMS MESSAGE", "61xxxxxxxxx")

Where 61xxxxxxxxx is the recipient’s mobile number in international format. For example, 61 is the country code for Australia, followed by 9 digits. That’s it! For example, you could save the script above as sms_alert.rb and call it directly from the bash status check script like so:

./sms_alert.rb

Make sure you make your file executable:

chmod +x sms_alert.rb

To check the number of SMS credits remaining on your account:

#!/usr/bin/env ruby

require 'rubygems'
require 'smsify'
 
smsify = SMSify.new("your_api_key")
smsify.getSMSCredits()