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

Mar*_*son 12 iterm

如何从命令行运行iTerm会话,传入要在iTerm窗口中执行的命令?

xterm模拟是-e,即

xterm -e sleep 10
Run Code Online (Sandbox Code Playgroud)

小智 12

我找到了官方文档,但没有想过用像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
Run Code Online (Sandbox Code Playgroud)

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

Sus*_*ver 7

我同意Alex的观点,使用AppleScript是最好的方法.

这是我的"iterm"脚本,我chmod作为可执行文件并将其放在我的路径中的目录中.我可以像这样使用它:

引用封闭的shell参数:

iterm "ls -l" 
Run Code Online (Sandbox Code Playgroud)

传递多个cmds以运行:

iterm "calculatesomthing" "exit"
Run Code Online (Sandbox Code Playgroud)

传递多个cmds,分号分隔:

iterm "cd ~/mediaprojects; ./gitSyncAll; exit" 
Run Code Online (Sandbox Code Playgroud)

自封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 ``-'' $@
Run Code Online (Sandbox Code Playgroud)

仅供参考:您可能想要删除"说"命令,我将其用作正在执行的每个cmd的远程/可听通知.我将一堆cmds传递给多个自定义的iTerm配置文件/ shell,这些配置文件/ shell将平铺到大型平面屏幕以显示复杂的多DC Azure部署的状态...

PS:我添加了一个要点,因为脚本的最后一行中的引号没有为某人正确剪切/粘贴@ https://gist.github.com/sushihangover/7563e1707e98cdf2b285

  • 我收到错误:78:86:执行错误:变量终端未定义。(-2753)。我正在使用 iterm2。有什么建议吗? (2认同)

Ale*_*lex 5

最好使用Applescript。iTerm2有一些脚本示例。该文档有点伪劣,但是这些示例应该使您对从何开始有所了解。

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

#~/bin/bash
tell application "iTerm"
    # etc...
    exec command "$@"
Run Code Online (Sandbox Code Playgroud)

然后,运行脚本非常简单:

./run-in-iterm.sh "echo 'hello world'"
Run Code Online (Sandbox Code Playgroud)