2

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?

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

Try:

tell application "Terminal"
    if not (exists window 1) then reopen
    activate
    do script "echo hi" in window 1
end tell
| improve this answer | |
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.)

| improve this answer | |

You must log in to answer this question.