If the script could also be run when you open a file (or in other cases), you could use opensnoop.
~/test:
#!/bin/bash
while :; do
opensnoop | grep -Ev ' (mdworker|mds|filecoordinatio|revisiond|Finder|Alfred) ' | grep -m1 '/Users/username/Folder/.*\.txt'
say a
sleep 1
done
/Library/LaunchAgents/test.plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd>
<plist version="1.0">
<dict>
<key>Label</key>
<string>test</string>
<key>Program</key>
<string>/Users/username/test</string>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
chmod +x ~/test
, sudo chown root /Library/LaunchAgents/test.plist
, and launchctl load /Library/LaunchAgents/test.plist
.
The argument for osascript -e
can contain newlines:
osascript -e 'set x to "a"
say x'
You can also specify multiple -e
arguments:
osascript -e 'set x to "a"' -e 'say x'
Or if you use a heredoc, bash
interprets three characters (\
, $
, and `
) between <<END
and END
but no characters between <<'END'
and END
.
osascript <<'END'
set x to "a"
say x
END
Edit:
Since osascript can operate with a heredoc (ie take input from /dev/stdin) then one can just write the script as a whole file and prepend with the correct shebang line:
#!/usr/bin/env osascript
set x to "a"
say x
This also allows you to save your apple script as a actual program in ~/Applications/.app using the following procedure (changing for your script's name):
mkdir -p ~/Applications/<APP_NAME>.app/Contents/MacOS
touch ~/Applications/<APP_NAME>.app/Contents/MacOS/<APP_NAME>
open -A TextEdit ~/Applications/<APP_NAME>.app/Contents/MacOS/<APP_NAME>
Ensure that both the script file in .../MacOS/ and the matches
Best Answer
After some searching, I found SleepWatcher, a free tool that allows to run a script when the screen goes to sleep or wakes up.
After installing it, you can link a shell script that is run on one of the available events (which include dim screen, wake up screen, computer sleep, wake up computer and some more). From the shell script, I can run a command, or call an AppleScript that I want to run on these events.
Since my screen goes to sleep when I lock my computer, this is exactly what I was looking for.
You can see it in action here: https://github.com/nwinkler/sleepwatcher-lync-status