Skip to content

Instantly share code, notes, and snippets.

@dusenberrymw
Last active December 4, 2023 20:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dusenberrymw/b707d35c2992a30e48947c3bf920fcce to your computer and use it in GitHub Desktop.
Save dusenberrymw/b707d35c2992a30e48947c3bf920fcce to your computer and use it in GitHub Desktop.
Automatically force OS X / macOS to sleep when the battery is low (script + plist).
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>mwd.sleepMac</string>
<key>ProgramArguments</key>
<array>
<string>/path/to/sleepMac.sh</string>
</array>
<key>StartInterval</key>
<integer>60</integer>
</dict>
</plist>
#!/bin/bash
# Automatically force your Mac to sleep when the battery is low.
#
# This script will check if the battery percentage is < 10, and if so,
# will launch a dialog informing the user that the system will sleep
# in 30 seconds unless the user clicks "No". This is useful for making
# sure the system does not accidentally stay awake and then completely
# die due to fully exhausting the battery.
#
# Protip: This works even when using `caffeinate -di` to keep OS X awake.
#
# This will need to be paired with the `mwd.sleepMac.plist` file stored
# at `~/Library/LaunchAgents/`.
#
# Installation:
# Move `sleepMac.sh` to a folder of your choice, and edit `mwd.sleepMac.plist`
# to reflect that.
# Then:
# ```
# mv mwd.sleepMac.plist ~/Library/LaunchAgents/
# chmod +x sleepMac.sh
# launchctl load -w ~/Library/LaunchAgents/mwd.sleepMac.plist
# launchctl list # optional to check that it is in the list
# launchctl start mwd.sleepMac # optional to kick-start task immediately
# ```
percentage_threshold=10
if (pmset -g batt | grep -q "from 'Battery"); then
percentage=$(pmset -g batt | grep -o "[0-9]*%" | grep -o "[0-9][0-9]*");
if (($percentage < $percentage_threshold)); then
# battery is low
osascript -e 'tell app "Finder" to activate';
n=$(osascript -e 'tell app "Finder" to display dialog "Battery dying! Your computer will sleep in 30 secs." buttons {"No"} giving up after 30
if button returned of result = "No" then
return 1
end if');
echo $n;
if (($n)); then
echo "cancelled";
else
if (pmset -g batt | grep -q "from 'Battery"); then
echo "ejecting all external hard drives...."
osascript -e 'tell application "Finder" to eject (every disk whose ejectable is true)'
echo "sleeping...";
pmset sleepnow
fi
fi
fi
fi
@udp1024
Copy link

udp1024 commented Nov 6, 2023

I wish there was a +1 button here 👍

This is a very useful script. Thank you

@dusenberrymw
Copy link
Author

Thanks, glad it was helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment