How can I prevent idle sleep in a long-running bash script on Mac OS?
Asked Answered
Y

1

9

I have a bash script that executes several long-running commands on Mac OS. How can I prevent the computer from going to sleep while the script is running?

Yellowlegs answered 14/2, 2021 at 23:47 Comment(0)
Y
20

I found that I can achieve the desired behavior by adding this line to the start of the script:

caffeinate -i -w $$ &

How it works:

  • caffeinate is a built-in Mac OS utility for creating power management assertions to prevent sleep.
    • The -i flag tells caffeinate to prevent idle sleep.
    • The -w flag tells caffeinate to wait until the specified process finishes.
    • $$ is a shell variable containing the current PID. Together with the -w flag this tells caffeinate to prevent sleep for the duration of the shell script.
  • The final & runs the command in the background so the script can continue running.
Yellowlegs answered 14/2, 2021 at 23:47 Comment(1)
-i is superfluous because it's already the default.Zabaglione

© 2022 - 2024 — McMap. All rights reserved.