Website downtime can lead to loss of revenue, customers, and credibility. This Bash script checks the availability of a website by pinging its URL and logs the status. It can also send an email notification if the site is down.

Step-by-Step Guide:

1. Define Variables: Specify the website URL, email address for alerts, and log file location.

URL="http://example.com"

EMAIL="your_email@example.com"

LOG_FILE="/var/log/website_status.log"

2. Check Website Availability: Use curl to check the HTTP status code of the website.

STATUS=$(curl -o /dev/null -s -w "%{http_code}\n" $URL)

3. Log the Status: Record the status in the log file and send an email if the site is down.

DATE=$(date +"%Y-%m-%d %H:%M:%S")

if [ $STATUS -ne 200 ]; then

echo "$DATE - $URL is down. Status code: $STATUS" >> $LOG_FILE

echo "$URL is down. Status code: $STATUS" | mail -s "Website Down Alert" $EMAIL

else

echo "$DATE - $URL is up. Status code: $STATUS" >> $LOG_FILE

fi

Complete Script:

#!/bin/bash

# Variables

URL=“http://example.com”

EMAIL=“your_email@example.com”

LOG_FILE=“/var/log/website_status.log”

# Check website availability

STATUS=$(curl -o /dev/null -s -w “%{http_code}\n” $URL)


# Log status

DATE=$(date +"%Y-%m-%d %H:%M:%S")

if [ $STATUS -ne 200 ]; then

echo "$DATE - $URL is down. Status code: $STATUS" >> $LOG_FILE

echo "$URL is down. Status code: $STATUS" | mail -s "Website Down Alert" $EMAIL

else

echo "$DATE - $URL is up. Status code: $STATUS" >> $LOG_FILE

fi

Usage:

  • Replace http://example.com with the URL of the website to check.
  • Replace your_email@example.com with your email address.

This script helps you monitor your website’s availability and ensures you are quickly informed of any downtime.

 

To run it periodically, you might want to add this script to crontab.