MacOS – How to control the Terminal in the current space with AppleScript

applescriptcommand linemacosspacesterminal

Working on building a Handler that passes the terminal window then calls the ID for a script I've run into mixed results and I'm curious if there is a cleaner way to get window 1

The handler:

on termHandler()
    set activeTerminal to ""
    if application "Terminal" is running then
        tell application "Terminal"
            if not (exists window 1) and not busy of window 1 then
                activate
                tell application "Terminal" to do script "echo snow" in window 1
            else
                tell application "Terminal" to do script "date" in window 1
                set activeTerminal to window 1
                return activeTerminal
            end if
            do script "echo foo"
            activate
            set activeTerminal to window 1
            return activeTerminal
        end tell
    else
        tell application "Terminal"
            activate
            do script "echo bar" in window 1
            set activeTerminal to window 1
            return activeTerminal
        end tell
    end if
end termHandler

Everything I've read and researched:

Suggests that AppleScript and Terminal do not get along. My current OS is Sierra I'm writing this in but other boxes I have run Yosemite which would use this script. My end goal here is to identify a Terminal window in that particular space and fire some do script but I seem to be having an issue doing so. Is there an easier way to identify if the Terminal is running, not create a new window and if it is running return the window 1 as a variable so I can pass it do script?

Best Answer

Do you need to actually have it input into a terminal window or is that just the way that you found it to work? I am not sure if you are aware of this or not but you can run shell scripts directly from an AppleScript by using this "do shell script" command. As an example:

do shell script "echo snow"