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

19,465

Solution 1

The following does almost what you asked for, but it opens a new window.

tell application "iTerm"
    set newWindow to (create window with default profile)
    tell current session of newWindow
        write text "cd ~/Desktop; clear; pwd"
    end tell
end tell

(This was based on the new iTerm documentation and the below answer, which you should upvote!)

Solution 2

If anyone in 2020 looking for answer to this, find below:

tell application "iTerm"
    set newWindow to (create window with default profile)
    tell current session of newWindow
        write text "cd ~/Desktop; clear; pwd"
    end tell
end tell
Share:
19,465

Related videos on Youtube

cwd
Author by

cwd

Updated on September 18, 2022

Comments

  • cwd
    cwd over 1 year

    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.

  • HikeMike
    HikeMike almost 13 years
    write text adds the return/newline on its own?
  • slhck
    slhck almost 13 years
    Apparently, it does! I tried everything before posting. exec command does something, but I don't know what exactly.
  • cwd
    cwd almost 13 years
    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: code.google.com/p/iterm2/wiki/AppleScript
  • Henrik N
    Henrik N over 11 years
    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.
  • Ken
    Ken almost 10 years
    @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
    Ken almost 10 years
    @slhck nvm, found this little gem with EOD usage:apple.stackexchange.com/questions/103621/…
  • Admin
    Admin almost 2 years
    This doesn't work anymore. The variable terminal is not defined
  • Admin
    Admin almost 2 years
    This doesn't work anymore. The variable terminal is not defined