4

What I'm doing

I'm using iTerm2 Build 3.0.15 and writing a script that opens a new window and prints "hello world" to the screen. Really, I'm interested in being to run any command but using echo "hello world" as a starting point.

What I've tried

I read up on the iTerm2 documentation for scripting. I wanted to learn more so I dragged the iTerm2 icon on the Script Editor icon to view the dictionary available to me and found the following command:

enter image description here

From reading the dictionary and documentation I wrote the following script:

tell application "iTerm"
  create window with default profile command "echo hello world"
end tell

When I run my script from the terminal a new window opened and "hello world" was on the screen; however, I got the following broken pipe error: enter image description here

When I select Ok the window closed and I'm left with the following message:

$ osascript iterm.applescript
window id 6415

The Questions

  • What do these broken pipe and window id 6415 errors mean?
  • How do I write a script that opens an iTerm2 window and runs a command?
  • delay 1 write text "clear" is nice if you want a clean start – jeremyjjbrown May 8 '18 at 14:10
3

Try this:

tell application "iTerm2"
    set newWindow to (create window with default profile)
    tell current session of newWindow
        write text "echo it works!"
    end tell
end tell

The write command, when not using without newline, executes the write text command because of the default added newline after the "text to send". Thus the window stays open after the command completes, ready for additional use.


From the iTerm AppleScript Dictionary:

writev : Send text as though it was typed.

      write specifier : The session to send to
            [contents of file file] : Filename to send the contents of
            [text text] : Text to send
            [newline boolean] : If newline should be added to end of text (default: yes)

0

Replace command "echo hello world" with

command "bash -c \"echo hello world && read\""

The use of read makes bash wait for the user to end the line (i.e. by pressing enter) before exiting. Pressing enter within 3 seconds will still yield the warning, as this is an iTerm feature which you can disable by checking the box on the alert, and control more precisely in Preferences → Advanced → Warn about short-lived sessions.

  • @user Sure, edited – grg Jun 15 '17 at 21:06
  • 2
    Is it possible to not have the terminal close? The goal is to be able to say "Open iTerm run this command and don't quit" – mbigras Jun 15 '17 at 21:23

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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