Osascript display dialog hangs when screen is off; detect unavailable GUI/display from bash or applescript

applescriptbashlaunchd

NOTE: If you have this problem, the answer from @abc helps mitigate it–but there are still unknown conditions under which this solution won't keep the osascript from executing and hanging.

background

I've been working on a backup script that runs occasionally via launchd. When it runs, it prompts me with something like:

osascript -e "display dialog \"Is now a good time to back up?\""

This works great when the system is open/online, but it seems to hang if the lid is closed or screen is locked/off. A tolerable way to test this is to SSH into the system as the same user with the desktop active, run a command like the one above, and observe that the dialog pops up.

If I run the same command with the system locked, it just hangs. If I unlock/open the system, the command doesn't finish, and the dialog doesn't appear.

When running on battery power, I can simulate the same condition by running:

pmset displaysleepnow; osascript -e "display dialog \"never never land\""

question

Is anyone aware of a way to detect this condition (at launchd, bash, or applescript level) so that I can do any of:

  1. keep the job from running at all until the system is active
  2. sleep the script until I can display a dialog without it hanging
  3. abort the script run before it hangs

I'm not keen on it, but the best I've been able to figure out so far involves putting a long timeout on the first dialog in the script and bailing out if it never gets answered, i.e.:

osascript -e "display dialog \"Is now a good time to back up?\" giving up after 600"

Best Answer

This should keep waiting until the screen is on:

set screenOff to true
repeat until screenOff is false
    set screenOff to (do shell script "ioreg -c AppleBacklightDisplay | grep dsyp") contains "\"dsyp\"={\"min\"=0,\"max\"=2,\"value\"=0}"
end repeat

display dialog "Is now a good time to back up?"
Related Question