18

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.

2

3 Answers 3

16

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!)

7
  • write text adds the return/newline on its own?
    – Daniel Beck
    Jun 20, 2011 at 9:06
  • Apparently, it does! I tried everything before posting. exec command does something, but I don't know what exactly.
    – slhck
    Jun 20, 2011 at 9:19
  • 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
    – cwd
    Jun 21, 2011 at 4:16
  • 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
    Sep 5, 2012 at 13:44
  • 1
    @slhck nvm, found this little gem with EOD usage:apple.stackexchange.com/questions/103621/…
    – Ken
    Jun 22, 2014 at 16:30
5

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
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
1
  • This doesn't work anymore. The variable terminal is not defined
    – duplex143
    May 28 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.