3

I coded this little AppleScript using Automator:

tell application "Terminal"
do script "myscript"
end tell

This perfectly works but has a side effect: when I close the window, there's always the Terminal window to close, so there are two windows, the one that executes the script and the Terminal.

Is there any way to have just one window running?

2
  • 1
    What happens when You only make do script "myscript" ? Jan 25, 2016 at 19:15
  • @Mateusz Szolsek: I get an error
    – user165602
    Jan 26, 2016 at 7:24

3 Answers 3

5

Try:

tell application "Terminal"
    if not (exists window 1) then reopen
    activate
    do script "echo hi" in window 1
end tell
2

Looks like when Terminal is not open, then tell application Terminal opens the Terminal with first window and do script opens another window (because do script is supposed to open new window).

Partial solution is to do script ... in window 1, which forces to run the script in recently opened window, but when Terminal was in use before, this would hijack existing window (and possibly unsuitable context).

Following script did the trick for me:

if application "Terminal" is running then 
    tell application "Terminal"   
        # do script without "in window" will open a new window        
        do script "echo HELLO"             
        activate                          
    end tell                              
else                                      
    tell application "Terminal"   
        # window 1 is guaranteed to be recently opened window        
        do script "echo HELLO" in window 1 
        activate
    end tell
end if 

(I got inspiration from adayzdone's proposal, but it didn't work for me (in El Capitan). Looks like after tell application "Terminal" the condition not (exists window 1) never holds.)

0

I know this is 5 years late but I found the answer.

Here is my simplified answer for you. Change "" to my script variable. We must first launch the terminal to prevent a duplicate window bug cause by activate creating a new window after do script already created a new window. We cannot assume we can run in window 1 after activate as that window could be closing or running from another process. The best solution is the one I wrote and has 0 bugs:

tell application "Terminal"
    if not application "Terminal" is running then launch
    do script ""
    activate
end tell

Here is the full script I used for my Java library open terminal

on run argv
    set scpt to first item in argv
    set p to second item in argv
    tell application "Terminal"
        if not application "Terminal" is running then launch
        set newTab to do script scpt
        try
            if p is not equal to "" then set current settings of newTab to settings set p
        end try
        activate
    end tell
end run

You must log in to answer this question.