Skip to content

Instantly share code, notes, and snippets.

@nitrocode
Last active October 29, 2024 16:44
Show Gist options
  • Save nitrocode/6a03f19b24c4bd7c2aa7fd34fc00c493 to your computer and use it in GitHub Desktop.
Save nitrocode/6a03f19b24c4bd7c2aa7fd34fc00c493 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Thanks to Andrew Zhang in hangops on 2024-10-18
# Get the battery percentage
battery_info=$(pmset -g batt)
battery_discharging=$(echo "$battery_info" | grep discharging -c)
battery_percentage=$(echo "$battery_info" | grep -o "[0-9]*%" | tr -d '%')
# Check if the battery percentage is less than threshold
if [ "$battery_discharging" -eq "0" ]; then
# echo "Battery is charging"
exit 0
fi
if [ "$battery_percentage" -lt 10 ]; then
# echo "Battery is low"
osascript -e 'display notification "Battery is at '$battery_percentage'%. Sounding alarm" with title "Alert"'
# Use a system sound command (e.g., afplay) to play a sound as an alarm
afplay /System/Library/Sounds/Glass.aiff
# else
# echo "Battery is greater than 10"
fi

Ding laptop when under a battery percent

Context

Often times the low battery notification can be ignored. It notifies around ~10% and then someone can go off and do other things. Usually in a zoom, the laptop can suddenly die taking seconds or even minutes to come back online.

Solution

Use a shell script on a cron to notify every minute it's charging. Depending on the rate of discharge, this can be 10 or more dings before the laptop is dead.

  1. Setup a directory
    mkdir -p $HOME/scripts
  2. Download the battery.sh script
    wget \
      https://gist.githubusercontent.com/nitrocode/6a03f19b24c4bd7c2aa7fd34fc00c493/raw/battery.sh \
      -O $HOME/scripts/battery.sh
  3. Set the script to execute
    chmod +x $HOME/scripts/battery.sh
  4. Run the script as a test
    $HOME/scripts/battery.sh
  5. Setup crontab
    crontab -e
    * * * * * /Users/user/scripts/battery.sh

Notes

Every time a cron script runs echo, it will show up as a new message in mail. This is why the above echo calls have been commented out.

Last login: Mon Oct 28 16:13:06 on ttys000
You have new mail.
Held 4024 messages in /var/mail/user

If they have been commnted in, remove the mail.

rm /var/mail/$USER
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment