Putting the computer to sleep from a non-interactive script

I have a backup script scheduled to run every night with launchd. It is a basic shell script, so no AppleScript is involved at this stage. I have also configured Evergy Saver to wake up the computer slightly before the backup starts. This far things are working, but what I have not been able to achieve, is that I would like to put the computer back to sleep after the backup has finished. For this purpose, I have added this line to the shell script:

osascript -e ‘tell application “System Events” to sleep’

It does work if I run it manually, but not when it is run from launchd. My guess is that this is because it cannot reach the System Events application, because it is not run in an interactive mode. Is there a way to put the computer to sleep from this context?

Use pmset.

Thanks, Adam.

It seems that the sleep event has to be scheduled a little bit into the future, or otherwise it fails:

sudo pmset schedule sleep “date "+%D %T"
pmset: Error in scheduling operation

This is what I came up with:

sudo pmset schedule sleep “date "+%D %H:"``expr \date “+%M”` “+” 2`:00”

It takes the current date, adds 2 to the minutes, and uses 00 for the seconds. Now let’s see how well it works in my backup script.

I have configured my mac to wake up/power on every night slighty before the backup script kicks in. After backing up my files, the script checks from the log files whether the computer was awaken at that time, or whether it was already awake, because I had left it on for whatever reason. If it was asleep, and if there has been no user activity in the last 30 minutes, it should go back to sleep. The latter check is to make sure that the machine stays on if I happen to be working in the middle of the time. (Not that I should be, though.)