How do I set up an AppleScript to open a new iTerm2 tab and change the directory?

17

13

In OS X, how do I set up an AppleScript to

  • open a new iTerm2 tab
  • change to a directory
  • clear the console
  • echo the current directory

I had something like this before for regular Terminal, but I can't even find the scripting guide for iTerm2.

cwd

Posted 2011-06-20T05:38:53.617

Reputation: 13 508

If your trying this with iTerm2, the solution is posted here: https://stackoverflow.com/questions/38692346/new-tab-in-iterm2#_=_

– Andy Cochrane – 2017-04-25T02:57:21.130

1

Go to their website, click "Documentation", then click "Scripting". Or what do you mean by "scripting guide"?

– Daniel Beck – 2011-06-20T06:31:58.820

Answers

16

Daniel's solution somehow opens a new Window – also, the exec command statement does not work as expected. One has to write text instead.

Also, you have to use

launch session "Default Session" 

in order to get a new tab.

The following does what you asked for:

tell application "iTerm"
    make new terminal
    tell the current terminal
        activate current session
        launch session "Default Session"
        tell the last session
            write text "cd ~/Downloads; clear; pwd"
        end tell
    end tell
end tell

slhck

Posted 2011-06-20T05:38:53.617

Reputation: 182 472

@slhck I'm having a hell of a time formatting this to be able to execute with osascript -e in the shell. Any advice? – Ken – 2014-06-22T16:26:54.260

1

@slhck nvm, found this little gem with EOD usage:http://apple.stackexchange.com/questions/103621/run-applescript-from-bash-script

– Ken – 2014-06-22T16:30:25.217

write text adds the return/newline on its own? – Daniel Beck – 2011-06-20T09:06:21.090

Apparently, it does! I tried everything before posting. exec command does something, but I don't know what exactly. – slhck – 2011-06-20T09:19:14.590

Thanks for a nice answer. I also found the comments at the bottom of this page to be helpful in writing a "cd to" script: http://code.google.com/p/iterm2/wiki/AppleScript

– cwd – 2011-06-21T04:16:06.770

I believe exec actually runs exec(3) and so only works in a new session, and runs the exec:ed process instead of a shell.

– Henrik N – 2012-09-05T13:44:14.630

0

Not on a Mac right now, so it might not work 100% (adapted this answer of mine).

tell application "iTerm"
    activate
    set t to (make new terminal)
    tell t
        tell (make new session at the end of sessions)
            exec command "cd Downloads"
            exec command "clear"
            exec command "pwd"
        end tell
    end tell
end tell

You can probably concatenate the commands to

cd Downloads ; clear ; pwd

Daniel Beck

Posted 2011-06-20T05:38:53.617

Reputation: 98 421