How do I target and close a specific Terminal window in AppleScript?

Solution 1:

Based on this stackexchange answer you can store the window object then loop through.

You can then close the window you opened whether it is in focus or not.

    osascript <<EOF
    tell application "Terminal"
        set newTab to do script
        set current settings of newTab to settings set "Grass"
        set theWindow to first window of (every window whose tabs contains newTab)

        do script "$cmd" in newTab
        repeat
            delay 0.05
            if not busy of newTab then exit repeat
        end repeat

        repeat with i from 1 to the count of theWindow's tabs
            if item i of theWindow's tabs is newTab then close theWindow
        end repeat
    end tell
EOF

The set current settings of newTab to settings set "Grass" line isn't necessary - it is only to show the relevant window in a different colour.

Solution 2:

The way to do this is very simple, and I left a comment to this effect against an earlier question:

Depending what you wish to do, you might find the value of w in your AppleScript to be useful. The window that is created by do script returns an AppleScript reference to it (that you have assigned to w), which will be of the form tab 1 of window id <number>, where <number> is a five-or-so digit id number that remains fixed throughout the lifespan of the window. You have to ignore the fact that the reference always contains tab 1 of..., which is misleading since three tabs contained in a single window will all be tab 1 of... three distinct id numbers.

As you noticed, the close command does not apply to a tab, so you need the window id. The reference created from any do script command gives you tab 1 of window id..., so you will always be able to reference the window which any particular do script command is running in:

tell application id "com.apple.Terminal"
    set T to do script "echo $$" --> btw, there's the pid number of the window's sub-shell
    set W to the id of window 1 where its tab 1 = T
        .
        .
     (* doing other stuff *)
        .
        .
    close window id W
end tell