3

I'm trying to create a script which would open a iTerm2 window, split it into 3 panes vertically and run a few commands inside each of those panes.

Here's my attempt so far:

tell application "iTerm2"
  activate

  -- Create main window
  create window with default profile

  tell current session of current window
    set name to "frontend"
    write text "cd ~/Documents/frontendDir"
    split vertically with default profile
  end tell

  tell second session of current window -- ERROR HERE
    set name to "backend"
    write text "cd ~/Documents/backendDir"
    split vertically with default profile
  end tell

  tell third session of current window
    set name to "apollo-server"
    write text "cd ~/Documents/GitHub/apolloDir"
  end tell
end tell

The first part about creating the frontend seems to work as the window is correctly opened and the command cd ~/Documents/frontendDir is correctly executed in it. The window is also split vertically once as I'm pretty sure it stops executing when I try to access the second pane of my window.

I'm getting this error: iTerm got an error: Can’t get session 2 of current window

Thanks in advance

Saraband
  • 1,540
  • 10
  • 18
  • Does this answer your question? [Applescript (osascript): opening split panes in iTerm 2 and performing commands](https://stackoverflow.com/questions/22339250/applescript-osascript-opening-split-panes-in-iterm-2-and-performing-commands) – jalanb Jan 21 '20 at 16:18

1 Answers1

5

iTerm session objects are contained by tabs, not windows. Therefore, as you can see in the script snippet below, I've referenced each session to write to by way of the current tab of the current window:

tell application "iTerm"
    activate

    set W to current window
    if W = missing value then set W to create window with default profile
    tell W's current session
        split vertically with default profile
        split vertically with default profile
    end tell
    set T to W's current tab
    write T's session 1 text "cd ~/Desktop"
    write T's session 2 text "cd ~/Downloads"
    write T's session 3 text "cd ~/Documents"
end tell

As far as I can tell, you cannot set the name property of a session; it gets set to the title of the session's frame. You can reference each session either by its index (as I've done here); its id property; or its tty property; all of which are unique values.

As you can see, the index appears to be ordered by a session's creation:

iTerm on macOS

CJK
  • 5,732
  • 1
  • 8
  • 26