从命令行(Mac OS X)打开新的终端标签页

155

在Mac OS X的终端中,是否有可能从当前打开的标签页通过命令行打开一个新的标签页?

我知道在终端中打开新标签页的键盘快捷键是“CMD+t”,但我正在寻找一种基于脚本的解决方案,可以在命令行中执行。

15个回答

1
如果您正在使用,这个命令将会打开一个新的标签页:
osascript -e 'tell application "iTerm" to activate' -e 'tell application "System Events" to tell process "iTerm" to keystroke "t" using command down'

如果你需要将这个添加到.zshrc或者.bashrc中,你可以使用一个函数而不是别名(因为你最终会需要进行大量的转义)。 - Vigrant
@Andrew Schreiber : 但是控件没有转移到新选项卡中。我的意思是,如果你在打开新选项卡后有一些代码,那么这些代码将在原始选项卡中执行。有没有办法告诉脚本在新选项卡中处理以下命令? - Ashwin

0
另一个选项是使用make来更好地组织您的终端标签启动。例如,您可以创建一个类似于以下内容的make文件:

Makefile

.PHONY:launchtabgroup1
launchtabgroup1:
    chmod u+r+x scripts/launch_tabgroup1.sh
    scripts/launch_tabgroup1.sh

.PHONY:launchtabgroup2
launchtabgroup2:
    chmod u+r+x scripts/launch_tabgroup2.sh
    scripts/launch_tabgroup2.sh

然后在您存储make文件的子目录中创建一个脚本目录,其中包含打开该组所需的所有选项卡的所有命令。像这样:

launch_tabgroup1.sh

#!/usr/bin/env sh


osascript -e 'tell application "Terminal" to activate' \
  -e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down' \
  -e 'tell application "Terminal" to do script "cd ../path/to/desired/directory" in selected tab of the front window'

osascript -e 'tell application "Terminal" to activate' \
  -e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down' \
  -e 'tell application "Terminal" to do script "cd ../path/to/desired/directory" in selected tab of the front window'

osascript -e 'tell application "Terminal" to activate' \
  -e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down' \
  -e 'tell application "Terminal" to do script "cd ../path/to/desired/directory" in selected tab of the front window'

你需要在 Makefile 中创建相应的条目,调用对应的 .sh 文件来启动分组中的选项卡!

要实际启动选项卡分组,请导航到 Makefile 目录并运行 make launchtabgroup1make launchtabgroup2


0
我制作了一个简化版本,可以解决生成新UI的AppleScript错误。
on run argv
    set scpt to first item in argv
    set flag to application "Terminal" is not running
    tell application "Terminal"
        do script scpt
        activate
        delay 1.0E-5
        if flag then close back window
    end tell
end run

或者这个也可以

open -a Terminal.app path/file.sh

0

如果已经安装了X(例如从homebrew或Quartz),那么简单的“xterm&”就可以实现(几乎)所需功能,它会打开一个新的终端窗口(但不是选项卡)。


0
这个简单的片段怎么样,它基于一个标准脚本命令(echo):
# set mac osx's terminal title to "My Title"
echo -n -e "\033]0;My Title\007"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接