Check For Power Outage, Shell Script

I havea computer that runs 24/7. It is connected to a UPS (Uninterruptable Power Supply) so that it does go offline when there are momentary power outages. One problem that I had encountered is that when the power would go out, the system would not shut down as it should when the battery reached a certain level.

As a result, I created a shell script that would check to make sure that it could reach the router at all times. In the event that it could not reach the router after two attempts, it was safe to assume that the power had went out and that the computer would need to shut down. Otherwise the UPS battery would die and the computer would have an unclean shutdown, which is not a good thing.

Below is the script that I created that is ran by a cron job.

#!/bin/bash

## shutdown if router cannot be reached

TEST_PASS="N"
COUNT=0

while [[ ${TEST_PASS} == "N" ]] || [[ ${COUNT} -ge 2 ]]
do
    wget -q http://router

    RETURN_CODE=$?

    echo "Checking return code ${RETURN_CODE}"

    if [ ${RETURN_CODE} -ne 0 ]; then
        COUNT=$((${COUNT}+1))

        sleep 60
    else
        exit 0
    fi

    if [ ${COUNT} -ge 2 ]; then
        echo "do shutdown"
        shutdown -h now
        exit 1
    fi
done
Posted: 2023-06-03
Author: Kenny Robinson, @almostengr