在iTerm中打开新标签并在那里执行命令


17

我找到了在以下位置打开新标签的方法iTerm

newtabi()
{
    osascript -e 'tell application "iTerm" to activate' -e 'tell application "System Events" to tell process "iTerm" to keystroke "t" using command down'
}

我想在新标签页中执行一些命令。让它成为简单的命令pwd。怎么做?

如果我跑...

newtabi && pwd

新标签页按预期方式打开,但pwd命令不是在新标签页中执行,而是在我键入的旧标签中执行newtabi && pwd

我用zsh。我的操作系统是OS X 10.8.5

Answers:


16

用途tell session -1 of current terminal to write text "pwd"

activate application "iTerm"
tell application "System Events" to keystroke "t" using command down
tell application "iTerm" to tell session -1 of current terminal to write text "pwd"

1
如果打开了多个iTerms,它将在正确的iTerm实例中打开新选项卡,但pwd在iTerm的第一个实例的最后一个选项卡中写入
Maxim Yefremov

2
@efr你是对的。我将答案编辑terminal 1current terminal。现在,它应该在当前窗口而不是首先打开的窗口中运行命令。
Lri

2
这在使用iTerm2的mac 10.11.6上不起作用。在脚本编辑器中,突出显示“意外的行尾但找到了标识符”和“终端”
Mike Blandford

1
这不再适用于macOS 10.14:execution error: System Events got an error: osascript is not allowed to send keystrokes. (1002)
KernelSanders

12
osascript \
-e 'tell application "iTerm" to activate' \
-e 'tell application "System Events" to tell process "iTerm" to keystroke "t" using command down' \
-e 'tell application "System Events" to tell process "iTerm" to keystroke "ls"' \
-e 'tell application "System Events" to tell process "iTerm" to key code 52'

我正在148:156: syntax error: Expected end of line but found identifier. (-2741)做这个。
临时用户

4

从macOS Mojave开始,至少运行iTerm 3.2.8,如果您运行:

$ open -a iTerm .

它将作为选项卡添加到当前窗口。


1

我无法获得公认的答案。我还想传递多个命令。这就是我想出的。

newtabi(){  
  osascript \
    -e 'tell application "iTerm2" to tell current window to set newWindow to (create tab with default profile)'\
    -e "tell application \"iTerm2\" to tell current session of newWindow to write text \"${@}\""
}

用法示例

newtabi pwd
newtabi 'cd ~/ && pwd'
newtabi 'echo \"Hello New Tab\"'

对于更复杂的操作,我建议分解命令。

code_folder="/path/to/code"

alias project="cd ${code_folder}/my-project/foo && yarn run start"

然后, newtabi project


您能告诉我如何传递电流pwd以使命令看起来像:“ newtabi'$ PWD / foo && yarn run start”吗?
拉吉

1
@Raj,很好的问题。我个人将命令分解为更易用的别名和/或功能。我添加了另一个示例。希望能帮助到你!
马克·巴尔博

非常感谢@Marc!
拉吉(Raj)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.