Opening a new terminal tab and running a command in it

Greetings!

I’m trying to write a script that would open all the apps I need for a particular project. Right now I’m working in bash, but I wonder if I should be trying Apple Script. I don’t have much experience with either.

I need the script to open a new tab in iTerm and then run further commands in the new tab. If I write something like

open -a iTerm /Path/to/my/project;
echo 'banana';

I get a new tab in the appropriate place, but ‘banana’ shows up in the original iTerm tab (the one where I typed the command).

How can I run a command in the newly opened tab?

Thanks!

This thread on StackExchange describes some options, but note the discussed variations over time between OS version and iTerm version.

This post also sets out what I think is one of the neatest and most understandable approaches, so if this one works, perhaps go with that.

Hope that helps.

Thanks, but no luck so far. The Coderwall article looked like the perfect solution, but I get the error

The variable terminal is not defined.

(BTW, I’m not married to iTerm–it’s just what I generally use. If there’s a way to do this in the regular mac terminal, that’s fine too.)

Hmmm, okay. I guess some people do things a bit differently; I also got the error fo r the script you referenced. I assume you must have tried the others too from the first post and got similar results.

On that basis, I took a quick look at the iTerm AppleScript and I came up with the script below. It works for me with iTerm2 on High Sierra. It includes examples for creating windows and tabs, sending multiple commands in sequence to a tab.

tell application "iTerm"
	--Create initial window
	create window with default profile
	
	--Create a second tab in the initial window
	tell current window
		create tab with default profile
	end tell
	
	--Send a command to the first tab
	tell current session of tab 1 of current window
		write text "echo apple"
	end tell
	
	--Send a couple of commands to the second tab
	tell current session of tab 2 of current window
		write text "echo banana"
		write text "echo clementine"
	end tell
	
	--Send another command to the first tab
	tell current session of tab 1 of current window
		write text "echo pie"
	end tell
	
	--Select the first tab
	tell tab 1 of current window
		select
	end tell
end tell

I think that should give you what you need, assuming it works for you of course.

1 Like

This works beautifully! Thank you, @sylumer, for being so generous with your talent and time.