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.)
do script "myscript"
?