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.


## shutdown if router cannot be reached


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


    echo "Checking return code ${RETURN_CODE}"

    if [ ${RETURN_CODE} -ne 0 ]; then

        sleep 60
        exit 0

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