Applescript 或 Shell 用于关闭 OSX 中每个未使用的终端 window 的脚本

Applescript or Shell Script to close every not-in-use terminal window in OSX

我有一个应用程序 运行 在 OSX 的 UI 用户会话中(一个单声道应用程序 运行 在终端 window,一个命令行程序)。有时这个单声道应用程序出于任何原因退出,并且 shell 脚本在启动时每 2 分钟 运行s 检查是否 ps ax | grep "mono" 仅 returns grep 命令作为唯一单声道过程。如果是这样,生成一个新的终端 window 并在该终端中再次 window 运行 单声道程序。

无论如何,有时这会使大量终端 windows 处于打开状态。我想要的是附加到这个 shell 脚本或者在 Applescript 中,我可以在我的单声道应用程序中调用它来关闭每个终端 window 而不是 运行 宁一个单声道进程。 Applescript 可以确定终端 window 是否正在 运行 某个程序吗? shell 可以确定吗?如果可以,怎么做?

我看了这个post:osascript - How to close a Terminal tab using AppleScript? - Stack Overflow

tell application "Terminal"
    activate
    set wns to every window of it
    repeat with aWn in wns

        set theTabs to every tab of aWn
        repeat with i from (count theTabs) to 1 by -1
            set aTab to item i of theTabs
            if not (get busy of aTab) then
                tell aWn to set selected tab to tab i of aWn
                do script "exit" in tab i of aWn
            end if
        end repeat
    end repeat
end tell

如果进程不忙,那么显然 运行 目前没有任何事情,这是我对此的看法。

问题是,如果您的单进程 运行 在前台运行,终端正忙,那么我猜您 运行 的脚本将被搁置。您可以做的是提取终端 window 的输出(文本),并在那里寻找您的单声道进程。 (我真的觉得,关闭所有不忙的 windows 是最好的。假设你有一个工作 window,那么你可以为那个 window 分配一个 'special title' , 因此,使用 if 测试使其免于关闭。(它可能大部分时间都不忙。)

这个怎么样。

将 processCheckName 更改为您的进程

set processCheckName to "du"
tell application "Terminal"
    --activate
    set theWindows to every window of it
    repeat with thisWindows in theWindows
        set biglist to {}
        set theTabs to every tab of thisWindows
        repeat with i from 1 to number of items in theTabs
            set this_item to item i of theTabs
            set theProc to processes of this_item
            if theProc contains processCheckName then
                copy id of thisWindows to end of biglist
            end if
        end repeat
        if (id of thisWindows) is not in biglist then

            close thisWindows
        end if
    end repeat
end tell