1
tell application "Terminal"
    activate
    if windows is {} then reopen
    do script "ssh user@192.168.0.1" in window 1
end tell

How can I tell apple script if there are open windows, to open new window as well, because it can ruin existing one.

Pablo
  • 28,133
  • 34
  • 125
  • 215

2 Answers2

2

This is cleaner...

tell application "Terminal"
    if not (exists window 1) then reopen
    activate
    do script "ssh user@192.168.0.1" in window 1
end tell
adayzdone
  • 11,120
  • 2
  • 20
  • 37
0

If you don't target a window by index it will open a new window every time.

e.g,

tell application "Terminal"
    activate
    do script "ssh user@192.168.0.1"
end tell

or to deal with using existing windows on a fresh open.

tell application "System Events"
    if (count (processes whose bundle identifier is "com.apple.Terminal")) is 0 then
        tell application "Terminal"
            activate
            do script "ssh user@192.168.0.1" in window 0
        end tell
    else
        tell application "Terminal"
            do script "ssh user@192.168.0.1"
            activate
        end tell
    end if
end tell

more ideas here: http://hintsforums.macworld.com/archive/index.php/t-68252.html

adamh
  • 3,222
  • 1
  • 20
  • 16
  • oh sorry, you are right. But with this approach there is one problem. If application is not running at all, then script will open two windows - one is default in second the command will be run. How to tell it open one window? I think that's why I mentioned in my original script `window 1` – Pablo Sep 22 '13 at 10:34
  • It only opens 1 for me if terminal is not running (on 10.7), however if i have left windows open when i quit terminal, then get re-opened too. – adamh Sep 22 '13 at 10:47
  • On 10.8 if I close the last window, but not quit app, script will open 1 window. But if I close the last window AND quit app, script will open 2 windows. I think you are referring to first case. – Pablo Sep 22 '13 at 10:50
  • Moderner Way to check for a running application via AppleScript: http://stackoverflow.com/questions/16064957/how-to-check-in-applescript-if-an-app-is-running-without-launching-it-via-osa/16069999#16069999 –  Sep 23 '13 at 20:04