Opening a new terminal from the command line and running a command on Mac OS X?

Solution 1:

osascript -e 'tell app "Terminal"
    do script "echo hello"
end tell'

This opens a new terminal and executes the command "echo hello" inside it.

Solution 2:

This works, at least under Mountain Lion. It does initialize an interactive shell each time, although you can replace that after-the-fact by invoking it as "macterm exec your-command". Store this in bin/macterm in your home directory and chmod a+x bin/macterm:

#!/usr/bin/osascript

on run argv
   tell app "Terminal" 
   set AppleScript's text item delimiters to " "
        do script argv as string
        end tell   
end run 

Solution 3:

You can do it in a roundabout way:

% cat /tmp/hello.command
#! /bin/sh -
say hello
% chmod +x /tmp/hello.command
% open /tmp/hello.command

Shell scripts which have the extension .command and which are executable, can be double-clicked on to run inside a new Terminal window. The command open, as you probably know, is equivalent to double-clicking on a Finder object, so this procedure ends up running the commands in the script within a new Terminal window.

Slightly twisted, but it does appear to work. I feel sure there must be a more direct route to this (what is it you're actually trying to do?), but it escapes me right now.

Solution 4:

One liners are great

osascript -e 'tell app "Terminal" to do script "cd ~/somewhere"'

Chaining commands is great too

osascript -e 'tell app "Terminal" to do script "cd ~/somewhere &&
ls -al &&
git status -s && 
npm start"'