Skip to content

Instantly share code, notes, and snippets.

@vishalbasra
Created June 7, 2019 05:45
Show Gist options
  • Save vishalbasra/b56357d8d28ecd436f72b0a9c8e85100 to your computer and use it in GitHub Desktop.
Save vishalbasra/b56357d8d28ecd436f72b0a9c8e85100 to your computer and use it in GitHub Desktop.
A sleep runner for macos
# This prevents a macos/osx computer even when the lid is closed to prevent it going to sleep in a multi desktop set-up
# based off https://apple.stackexchange.com/users/9058/nohillside 's answer at https://apple.stackexchange.com/questions/219885/use-caffeinate-to-prevent-sleep-on-lid-close-on-battery
# store in /user/local/bin
#! /bin/bash
BATTERY_SLEEP=5 # in minutes
DEF_WAKE_LEN=32400 # in seconds - I'm on my computer for 9 hours usually
#***** determine timeout value *****
timeout_len=${DEF_WAKE_LEN:-32400} # see also https://unix.stackexchange.com/questions/122845/using-a-b-for-variable-assignment-in-scripts
# trap ctrl-c and call ctrl_c()
trap enable_sleep INT
function enable_sleep() {
# $1: <enter> = 0, timeout = 1, Ctrl-C = undef
#----- insert a newline for timeout or Ctrl-C -----
if [[ ${1:-1} -eq 1 ]]; then echo; fi
echo "Restoring previous battery sleep setting: $BATTERY_SLEEP"
echo "\n"
sudo pmset -b disablesleep 0
sudo pmset -b sleep $BATTERY_SLEEP
#----- sleep on timeout only -----
if [[ ${1:--1} -eq 1 ]]; then sudo pmset sleepnow; fi
exit
}
function prevent_sleep() {
echo
echo -n "Preventing sleep for $timeout_len seconds; press [^C] to restore settings and quit..."
echo "\n"
sudo pmset -b disablesleep 1
sudo pmset -b sleep 0
sleep $timeout_len
enable_sleep
}
prevent_sleep
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment