Skip to content

Instantly share code, notes, and snippets.

@thmsmlr
Created May 27, 2025 14:56
Show Gist options
  • Save thmsmlr/3cb3b4d2b67c0fb740ca97f733edc34b to your computer and use it in GitHub Desktop.
Save thmsmlr/3cb3b4d2b67c0fb740ca97f733edc34b to your computer and use it in GitHub Desktop.
Toggle Sleep on MacOS
#!/bin/zsh
#
# toggle-sleep.sh – Disable system sleep when on AC power; re-enable on battery.
#
# Requires: sudo privileges for `pmset`. Run `sudo visudo` and add a NOPASSWD
# rule if you want it to run unattended:
# youruser ALL=(ALL) NOPASSWD: /usr/bin/pmset
#
# Install with:
# */1 * * * * /opt/homebrew/bin/zsh -i -c '/Users/thomas/.local/bin/toggle-sleep > /Users/thomas/.local/log/toggle-sleep.log'
#
# Check current power source
power_source=$(pmset -g batt | awk -F"'" '/Now drawing from/{print $2}')
echo "Current time: $(date)"
echo "Power source: $power_source"
case "$power_source" in
"AC Power")
# Plugged in – disable sleep
sudo pmset -a disablesleep 1
echo "On AC power sleep disabled"
;;
"Battery Power")
# On battery – allow sleep again
sudo pmset -a disablesleep 0
echo "On battery sleep enabled"
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment