MacOS – open new tab in iTerm and execute command there

itermmacosterminal

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

Best Answer

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"