Can I execute a Terminal command in a new tab? It just occurred to me that it would be incredibly useful if I could type a command in one Terminal tab, and then execute it in a new background or foreground tab. For example, this would be awesome when editing files with nano. I could cd to a location and then quickly nano sys_201406271933.log, nano 415ab40ae9b7cc4e66d6769cb2c08106e8293b48.key two new background tabs. The alternative is to manually open two tabs and flip between them, using the mouse to copy-paste the long, unmemorable filenames.

I've spent about 30 minutes researching whether this is possible and found no satisfying answer.
iTerm 2 is a powerful replacement for Terminal.app and it has support for AppleScript. You can use AppleScript to tell it to run commands in a new tab or window.

For example, let's make a little AppleScript action that's callable. Enter the following in to the AppleScript Editor:

on run argv
    set AppleScript's text item delimiters to {" "}
    tell application "iTerm"
        make new terminal
        tell the current terminal
            activate current session
            launch session "Default Session"
            tell the last session
                write text argv as string
            end tell
        end tell
    end tell
end run


and then save it as a Script in ~/Documents/Scripts/run-in-new-iterm-tab.scpt. We can now call it from the command line like so:

/Users/ian
&gt; osascript ~/Documents/Scripts/run-in-new-iterm-tab.scpt ls ~/Documents/Scripts

/Users/ian
&gt;


and I get a new tab in my iTerm session with:

Last login: Thu Aug 28 22:17:17 on ttys003
ls /Users/ian/Documents/Scripts

/Users/ian
&gt; ls /Users/ian/Documents/Scripts
edit                         keep_drives_alive.sh         run-in-new-iterm-tab.scpt    touch-in-order.pl
find-missing-itunes-files.pl keep_drives_alive.sh~        start-utorrent.scpt          touch-in-order.pl~

/Users/ian
&gt;


Which is not too bad. There are some refinements you can make to the AppleScript like maintaining the current working directory when you call the command. But that's gets you in the ballpark.

If you use this hint in this question you can turn the whole thing in to a bash-wrapped script that's even easier to execute:

#!/usr/bin/env osascript

on run argv
    set AppleScript's text item delimiters to {" "}
    tell application "iTerm"
        make new terminal
        tell the current terminal
            activate current session
            launch session "Default Session"
            tell the last session
                write text argv as string
            end tell
        end tell
    end tell
end run


Save that to a spot on your PATH and make it executable and then you only need to run:

run-in-new-iterm-tab ls ~/Documents/Scripts


to get it to work.