Skip to content

Instantly share code, notes, and snippets.

@r10r
Forked from dusenberrymw/mwd.sleepMac.plist
Created December 4, 2023 20:25
Show Gist options
  • Save r10r/4eedb5563e1cdcf85c732b822d6fe66e to your computer and use it in GitHub Desktop.
Save r10r/4eedb5563e1cdcf85c732b822d6fe66e 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment