Open multiple tabs in iTerm2 with a specific directories

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

Tags:

Macos

Bash

Iterm2