MacOS Low Battery Warning

What You Need

Purpose

Makes an audible chime when the battery is below 20%.

Making the Shell Script

On your Mac, in a Terminal window, execute this command:
nano /Applications/low_battery.sh
Paste in this code:
#!/bin/bash

for i in {1..5}
do
    echo ""
    charging_level=$(pmset -g batt | grep -Eo "\d+%" | cut -d% -f1)
    charging_status=$(pmset -g batt | grep charging | cut -f4 -d" " | cut -f1 -d ";")
    echo "Cuttent charging level is $charging_level and Battery is $charging_status
    if [ "$charging_status" == "discharging" ];then
        if (( charging_level < 20 )); then
            echo "Battery is LOW and Less than 20% & Discharging"
            #amixer set 'Master' 100%
            afplay /System/Library/Sounds/Blow.aiff
        fi
    fi

    if (( charging_level < 10 )); then
        sleep 2;
    else
        sleep 5;
    fi
done
Press Ctrl+X, Y, Enter to save the file.

Execute this command to make the script executable:

chmod +x /Applications/low_battery.sh

Setting crontab to Use Nano

If you like vi, skip this step.

On your Mac, in a Terminal window, execute this command:

nano ~/.zshrc
At the end of the file, add this code:
alias crontab='EDITOR=nano /usr/bin/crontab'
export VISUAL="nano"
export EDITOR="nano"
Press Ctrl+X, Y, Enter to save the file.

Execute this command to make the change take effect:

source ~/.zshrc

Making a cron Job

This will run the script every 5 minutes to test your battery level.

On your Mac, in a Terminal window, execute this command:

crontab -e
Paste in this code:
*/5 * * * * /Applications/low_battery.sh
Press Ctrl+X, Y, Enter to save the file.

A box pops up. Click Allow.

References

Beep Alert when Battery is below 10% -- MacOS

Posted 6-11-24
Minor update to command order 6-14-24