Open multiple tabs in iTerm2 with a specific directories

I would like to know if this is possible.

I want to set up some script or command that will open 5 tabs and each tab that will open will have their own directory specified

All in the same window

tab 1: open ~/folderA1
tab 2: open ~/folderA2
tab 3: open ~/folderA3
tab 4: open ~/folderA4
tab 5: open ~/folderA5

This is on iTerm2 in Mac OS X.

I know I can do something like CMD+T and then open each of them using cd ~/folderA1 and so on, but if there is a command that I can set up or a script that after executing they will do that all at once I would love to know if there is a way to do so.


Update: Newer iTerm requires you to change the syntax, so this would look like:

tell application "iTerm"
    tell current window
        create tab with default profile
    end tell
    tell current tab of current window
        set _new_session to last item of sessions
    end tell
    tell _new_session
        select
        write text "cd \"$dir\""
    end tell
end tell

See also this answer here.


For older iTerm versions:

Taking the script from my answer here, you can do something like this:

launch () {
for dir in ~/folderA{1..5}; do
/usr/bin/osascript <<-EOF
tell application "iTerm"
    make new terminal
    tell the current terminal
        activate current session
        launch session "Default Session"
        tell the last session
            write text "cd \"$dir\""
        end tell
    end tell
end tell
EOF
done
}

To explain what's going on:

  • We create a shell function named launch, so you can put this in your ~/.bash_profile or wherever you want to have it executed at startup.

  • We loop over the result of the Bash brace expansion ~/folderA{1..5}, which gives you ~/folderA1 through ~/folderA5.

  • We call the iTerm2 AppleScript library through osascript to create a new tab, activate it, launch the default session, and cd to the specified directory.


itermocil can handle this.

With the following in a file called ~/.itermocil/foo.yml, the command itermocil foo would open 5 tabs in the specified folders. (This is a really simple layout though - itermocil can do much more than this.)

windows:
  - name: '1'
    root: ~/folderA1
    layout: even-horizontal
    panes:
      - focus: true
  - name: '2'
    root: ~/folderA2
    layout: even-horizontal
    panes:
      - focus: true
  - name: '3'
    root: ~/folderA3
    layout: even-horizontal
    panes:
      - focus: true
  - name: '4'
    root: ~/folderA4
    layout: even-horizontal
    panes:
      - focus: true
  - name: '5'
    root: ~/folderA5
    layout: even-horizontal
    panes:
      - focus: true