Bash Script which calls osascript stops working when run by launchd
Graphical User Session Required
The error occurs because the commands in your osascript
require a graphical user session. AppleScript requires a graphical user session to work.
The launchd
job is running as the root
user in a non-graphical user session.
Alternative Approach
In these situations, the typical approach is to split daemons in two parts – one computer wide and another within each graphical user session. A pipe or socket is frequently used to communicate.
Even as root
user, there are barriers that can not be crossed in macOS.