Bash Programming

bash script: Website Status Checker Script


#!/bin/bash

# List of websites to check
websites=("http://www.example1.com" "http://www.example2.com" "http://www.example3.com")

# Email address to receive alerts
email="youremail@example.com"

for site in ${websites[@]}; do
status_code=$(curl -Is $site | head -n 1 | cut -d" " -f2)

if [ $status_code -ne 200 ]; then
echo "Alert: $site is down with status code $status_code" | mail -s "Website Down Alert" $email
fi
done

A bash script is provided here that checks the status of a list of websites and sends email alerts for any sites that are down.

The script starts by defining an array variable `websites` that contains a list of URLs to check for their status. It also sets the `email` variable to the email address where alerts will be sent.

Next, the script iterates over each URL in the `websites` array using a `for` loop. For each site, it uses the `curl` command to send a HEAD request and retrieve the status code of the response. The status code is extracted using `head` and `cut` commands.

If the status code is not equal to 200 (indicating a successful response), the script generates an alert message containing the URL and the status code. This message is then sent via email using the `mail` command with the subject “Website Down Alert” to the specified email address.

This script can be scheduled to run periodically using tools like `cron` to monitor the status of websites and alert the appropriate personnel when issues are detected.