Glen Mazza Glen Mazza - 1 month ago 15
Bash Question

Running shell commands in ITerm2 without tab closing after completion

Probably a minor syntax issue that I'm getting wrong, but can't find the solution in the ITerm2 documentation. I'd like to create an applescript that opens an ITerm window with four tabs, each running various shell commands (ls, cd, echo, etc.) with the tab the remaining open after those commands have run. The opening tabs part is working fine, but it appears that as soon as the commands run, the tab closes (if I don't provide any commands, the tab will remain open.) For my script here:

tell application "iTerm2"
create window with default profile
tell current window
create tab with default profile command "echo abc"
create tab with default profile
create tab with default profile
end tell
end tell


Instead of "echo abc" what should I put there so the echo command will run in the tab, but leave me with a cursor for me to type in more commands instead of the tab immediately closing thereafter?

Answer

Instead of using the create tab ... command, use a separate write text command. For example, this is a script I use to open a terminal to a specific directory:

tell application "iTerm"
  create window with default profile
  tell current session of current window
    write text "cd " & directory & "; clear"
  end tell
end tell