从命令行打开一个新终端并在 Mac OS X 上运行命令?

zlo*_*log 33 terminal command-line macos

有没有办法从命令行打开新终端,并在新终端(在 Mac 上)上运行命令?

例如,类似的东西:

Terminal -e ls
Run Code Online (Sandbox Code Playgroud)

ls新终端中运行的位置。

LaC*_*LaC 31

osascript -e 'tell app "Terminal"
    do script "echo hello"
end tell'
Run Code Online (Sandbox Code Playgroud)

这将打开一个新终端并在其中执行命令“echo hello”。

  • 这可以稍微短一点:`osascript -e 'tell app "Terminal" to do script "echo hello"'` (5认同)
  • 我确信这对于 applescript 专家来说是显而易见的,但是启动任何程序的示例怎么样?基本上就像我可以做“xterm -e somecomnand” (2认同)
  • 如何设置新的终端窗口顶部处于活动状态? (2认同)
  • 如何在 shell 中但在 osa 脚本中沿着 `"$@"` 行传递参数? (2认同)

jas*_*ard 13

一个衬垫很棒

osascript -e 'tell app "Terminal" to do script "cd ~/somewhere"'
Run Code Online (Sandbox Code Playgroud)

链接命令也很棒

osascript -e 'tell app "Terminal" to do script "cd ~/somewhere &&
ls -al &&
git status -s && 
npm start"'
Run Code Online (Sandbox Code Playgroud)


Nor*_*ray 7

你可以用迂回的方式做到这一点:

% cat /tmp/hello.command
#! /bin/sh -
say hello
% chmod +x /tmp/hello.command
% open /tmp/hello.command
Run Code Online (Sandbox Code Playgroud)

具有扩展名.command且可执行的 Shell 脚本可以双击在新的终端窗口中运行。您可能知道,该命令open相当于双击 Finder 对象,因此此过程最终会在新的终端窗口中运行脚本中的命令。

有点扭曲,但它似乎确实有效。我确信必须有一条更直接的途径来实现这一点(你实际上想做什么?),但现在我无法理解。


小智 6

这是有效的,至少在 Mountain Lion 下是这样。它每次都会初始化一个交互式 shell,尽管您可以通过将其调用为“macterm exec your-command ”来替换该 shell。将其存储在主目录中的 bin/macterm 中并 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 
Run Code Online (Sandbox Code Playgroud)