Skip to content

Instantly share code, notes, and snippets.

@b-
Last active September 4, 2018 03:38
Show Gist options
  • Save b-/c4effaca0ac8bcc50a58b3eabb2e50c5 to your computer and use it in GitHub Desktop.
Save b-/c4effaca0ac8bcc50a58b3eabb2e50c5 to your computer and use it in GitHub Desktop.
Hibernate macOS computer

deepsleep.sh: hibernate macOS computer

There is no easy way to hibernate a macOS computer on demand. This utility fixes that problem. This command must be run as root, but there's an easy way to fix that:

  • Copy deepsleep.sh to a folder, such as /usr/bin (In Terminal, type cp /PATH/TO/deepsleep.sh /usr/bin)
  • In Terminal, type: sudo visudo to edit the /etc/sudoers file. DO NOT edit this file with another command. If you do not like vi you can type export VISUAL=nano first to tell visudo to use nano
  • Add a line anywhere in the file (I recommend either the very beginning or very end) that says ALL ALL=NOPASSWD:/LOCATION/TO/deepsleep.sh (so, for example, ALL ALL=NOPASSWD:/usr/bin/deepsleep.sh)
  • Run the command using sudo /path/to/deepsleep.sh

WARNING:

If you wake the computer before it's finished hibernating, this script will leave it in a bad spot where it will hibernate every time you tell it to go to sleep. To fix this, type sudo pmset -a hibernatemode 3 or sudo path/to/deepsleep.sh fix into Terminal.

#!/bin/bash
if [ `whoami` != 'root' ]; then
echo Must be run as root!
exit 1
fi
if [ $1 == "fix" ]; then
echo "Fixing hibernatemode."
pmset -a hibernatemode 3
echo hibernatemode is now $(pmset -g | grep hibernatemode | tr -s "[:blank:]" | cut -d" " -f3)
exit 0
fi
hibernatemode=$(pmset -g | grep hibernatemode | tr -s "[:blank:]" | cut -d" " -f3)
echo hibernatemode is $hibernatemode
echo setting hibernatemode to 25
pmset -a hibernatemode 25 force
echo hibernatemode is now $(pmset -g | grep hibernatemode | tr -s "[:blank:]" | cut -d" " -f3)
#echo waiting 10 seconds
#sleep 10s
echo sleeping now
pmset sleepnow
echo waiting for computer to try and sleep
until [ $SECONDS -ge 35 ] ; do
sleep 2s
done
#shutdown -s now
#osascript -e 'tell application "System Events" to sleep'
echo putting display to sleep
pmset displaysleepnow
echo sleeping 1 seconds
sleep 1s
echo waking display
caffeinate -u &
echo setting hibernatemode back to $hibernatemode
pmset -a hibernatemode $hibernatemode
echo hibernatemode is now $(pmset -g | grep hibernatemode | tr -s "[:blank:]" | cut -d" " -f3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment