6

Im using Iterm2 version Build 3.0.4 I want to create alias to open new tab from the command line (in bash) I tried this code:

    function tab () {
    osascript &>/dev/null <<EOF
activate application "iTerm"
    tell application "System Events" to keystroke "t" using command down
    tell application "iTerm" to tell session -1 of current terminal to write text "pwd"
EOF
}

but it isn't working. Can anyone solve the problem with this version (or newer version)?

Dkova
  • 1,087
  • 4
  • 16
  • 28

2 Answers2

15

iTerm2 v3 features much-improved AppleScript support, so you can now create tabs directly, without having to send keystrokes:

tab() {
    osascript &>/dev/null <<EOF
      tell application "iTerm"
        activate
        tell current window to set tb to create tab with default profile
        tell current session of current window to write text "pwd"  
      end tell
EOF
}

To split the new tab horizontally (as you would get by pressing ⇧⌘D), add:

tell current session of current window to split horizontally with same profile

To write pwd to the new session created by the split (the lower half of the new tab):

tab() {
    osascript &>/dev/null <<EOF
      tell application "iTerm"
        activate
        tell current window to set tb to create tab with default profile
        tell current session of current window to set newSplit to split horizontally with same profile
        tell newSplit
          select
          write text "pwd"
        end tell    
      end tell
EOF
}

To browse iTerm2's available AppleScript commands, open Script Editor.app, select File > Open Dictionary..., and then iTerm.app.

Also consider my ttab CLI, which packages tab / window creation along with advanced features for both Terminal.app and iTerm2.app (but it doesn't support splitting a tab).

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • The code to execute `pwd` in the **split session did not work** for me. Replace `tell newSplit` with `tell second session of current tab of current window`. From [this answer](https://stackoverflow.com/a/28512260/4974372). You can also remove the `set newSplit to` part of the _split horizontally_ command. **To split the current session** (without creating new tag), remove the entire _create tab_ line. – Tobias Geisler May 20 '19 at 14:00
  • @TobiasGeisler: It's been a while since I've looked at this, but both functions seem to work fine on my macOS 10.14.5 machine running iTerm 3.2.9. – mklement0 May 21 '19 at 02:34
  • 1
    `ttab` can be brewed and is a very simple option – xverges Mar 04 '21 at 20:54
0
tell application "iTerm"
activate
tell current window to create tab with default profile
tell session of current tab of current window
    select
    write text "pwd"
end tell

end tell

Yongqiang Zhou
  • 322
  • 1
  • 12