17

I have found way to open new tab in iTerm:

newtabi()
{
    osascript -e 'tell application "iTerm" to activate' -e 'tell application "System Events" to tell process "iTerm" to keystroke "t" using command down'
}

And I want to execute some commands in new tab. Let it be simple command pwd. How to do it?

If I run ...

newtabi && pwd

The new tab is opened as expected, but pwd command is executed not in new tab but in old one, where I typed newtabi && pwd

I use zsh. My os is OS X 10.8.5

16
+50

Use tell session -1 of current terminal to write text "pwd":

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"
  • 1
    if opened more than one iTerms, it opens new tab in correct iTerm instance, but writes pwd in last tab of first instance of iTerm – Maxim Yefremov Nov 27 '13 at 15:16
  • 2
    @efr You're right. I edited the answer to change terminal 1 to current terminal. Now it should run the command in the current window instead of the window that was opened first. – Lri Nov 27 '13 at 15:40
  • 2
    This did not work on mac 10.11.6 with iTerm2. In script editor, "Unexpected end of line but found identifier" and "terminal" is highlighted – Mike Blandford Sep 5 '17 at 15:50
  • This no longer works on macOS 10.14: execution error: System Events got an error: osascript is not allowed to send keystrokes. (1002) – KernelSanders Feb 3 at 22:48
12
osascript \
-e 'tell application "iTerm" to activate' \
-e 'tell application "System Events" to tell process "iTerm" to keystroke "t" using command down' \
-e 'tell application "System Events" to tell process "iTerm" to keystroke "ls"' \
-e 'tell application "System Events" to tell process "iTerm" to key code 52'
  • I'm getting 148:156: syntax error: Expected end of line but found identifier. (-2741) on this. – temporary_user_name Apr 12 at 15:32
4

As of at least macos Mojave, iTerm 3.2.8, if you run:

$ open -a iTerm .

It will add it as a tab to the current window.

0

I couldn't get the accepted answer to work. I also wanted to pass multiple commands. This is what I came up with.

newtabi(){
  osascript \
  -e 'tell application "iTerm2" to tell current window to set newWindow to (create tab with default profile)'\
  -e "tell application \"iTerm2\" to tell current session of newWindow to write text \"${@}\""
}

Example usage

newtabi pwd
newtabi 'cd ~/ && pwd'
newtabi 'echo \"Hello New Tab\"'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .