Applescript–execute multi line code
Asked Answered
I

3

12

I have some apple script code:

tell application "System Events"
    key code 97
end tell

How do i write the code as a osascript -e command in Terminal? Everytime I try using \n or the such, I get errors. Sorry if I'm not being specific enough.

Illegitimate answered 22/8, 2015 at 13:27 Comment(0)
S
28

You have a couple of options:

  1. Pass each line of the AppleScript code as a separate -e option:

    osascript -e 'tell application "System Events"' -e 'key code 97' -e 'end tell'
    
  2. Pipe the AppleScript code to osascript's STDIN:

    osascript <<END
      tell application "System Events"
        key code 97
      end tell
    END
    

Oh, and you can also save AppleScript code as an executable shell script. Just add #!/usr/bin/osascript at the top of the code and save it as a plain text file:

#!/usr/bin/osascript

tell application "System Events"
  key code 97
end tell
Scrag answered 22/8, 2015 at 13:47 Comment(0)
T
1

Other example:

  open -a Terminal && \
     sleep 2 && \
     osascript -e 'activate application "Terminal"' -e 'tell application "System Events" to keystroke "q" using command down'

the first two lines are just to show the final goal, which is focus the Terminal window and quit it, sending Command+q

Truck answered 23/6, 2017 at 21:41 Comment(0)
V
1

Actually -e option accepts new lines:

osascript -e '
tell application "System Events"
    key code 97
end tell'
Vergievergil answered 31/12, 2017 at 1:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.