如何从命令行在iTerm窗口执行命令?

13

我该如何从命令行运行一个iTerm会话,并在其中传入要在iTerm窗口中执行的命令?

xterm的对应命令是-e,即:

xterm -e sleep 10
3个回答

17

我已经找到了官方文档,但是没有像SushiHangover那样使用osascript来包裹Applescript。他的回答对我不起作用,可能是因为我正在使用最新的beta 3.0版本,所以这里有一个可以工作的方案(也稍微简化了一下)。

#!/bin/bash
osascript - "$@" <<EOF
on run argv
tell application "iTerm"
    activate
    set new_term to (create window with default profile)
    tell new_term
        tell the current session
            repeat with arg in argv
               write text arg
            end repeat
        end tell
    end tell
end tell
end run
EOF

2
谢谢。根据您的回答,我编写了一个脚本来将文本写入当前会话。https://gist.github.com/LeoUfimtsev/82e7e827b6bfb1000f422a98f2008cc3 - Leo Ufimtsev

9

我同意Alex的看法,使用AppleScript是最好的选择。

以下是我的“iterm”脚本,我将其chmod为可执行文件并放在路径中。我可以像这样使用它:

引用封闭的shell参数:

iterm "ls -l" 

传递多个命令以运行:
iterm "calculatesomthing" "exit"

传递多个命令,以分号分隔:
iterm "cd ~/mediaprojects; ./gitSyncAll; exit" 

这是自包含的Bash / Applescript:

#!/bin/bash
read -r -d '' script <<'EOF'
on run argv
tell application "iTerm"
    activate
    set myterm to (make new terminal)
    tell myterm
        launch session "Default"
        tell the last session
            repeat with arg in argv
               say arg
               write text arg
            end repeat
        end tell
    end tell
end tell
end run
EOF
echo "$script" | osascript ``-'' $@

FYI:您可能想要删除“say”命令,我将其用作每个cmd被执行的远程/可听通知。我将一堆cmds传递给多个自定义iTerm配置文件/ shell,这些配置文件/ shell会平铺到一个大型平面屏幕上,以显示复杂的多DC Azure部署的状态...
PS:我添加了一个 gist,因为脚本最后一行的引号未能正确剪切/粘贴给https://gist.github.com/sushihangover/7563e1707e98cdf2b285上的某些人。

4
我遇到了错误:78:86: 执行错误:变量 terminal 未定义。 (-2753)。我正在使用 iterm2 终端。有什么建议吗? - Leo Ufimtsev

5

最好使用Applescript来完成此操作。iTerm2有一些脚本示例。文档有点不完整,但这些示例可以让您了解从何处开始。

您可以将Applescript字符串包装在bash脚本中,然后使用osascript启动它:

#~/bin/bash
tell application "iTerm"
    # etc...
    exec command "$@"

然后运行该脚本就像这样简单:

./run-in-iterm.sh "echo 'hello world'"

1
我同意,AppleScript 是一个好的选择,我添加了一个答案,其中包含我使用的自封闭 bash/AppleScript 脚本。 - SushiHangover
1
谢谢,这里是最新版本iTerm2的示例:https://iterm2.com/documentation-scripting.html - abumalick

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