4

我正在使用 AppleScript 在终端选项卡中打开 PostgreSQL,如下所示:

#!/bin/bash

function new_tab() {
  TAB_NAME=$1
  COMMAND=$2
  osascript \
    -e "tell application \"Terminal\"" \
    -e "tell application \"System Events\" to keystroke \"t\" using {command down}" \
    -e "do script \"printf '\\\e]1;$TAB_NAME\\\a'; $COMMAND\" in front window" \
    -e "end tell" > /dev/null
}

new_tab "PostgreSQL" "postgres -D /usr/local/var/postgres"

从终端运行此脚本将打开一个新选项卡,其中包含 PostgreSQL 服务器。所以在执行结束时,我将有 2 个选项卡:第一个用于运行脚本,第二个包含服务器。

我怎样才能关闭第一个?

这是我的尝试:

osascript -e "tell application \"Terminal\" to close tab 1 of window 1"

但我收到此错误消息:

执行错误:终端出现错误:窗口 1 的选项卡 1 不理解“关闭”消息。(-1708)

4

5 回答 5

4

你可以尝试这样的事情:

tell application "Terminal"
    activate
    tell window 1
        set selected tab to tab 1
        my closeTabOne()
    end tell
end tell


on closeTabOne()
    activate application "Terminal"
    delay 0.5
    tell application "System Events"
        tell process "Terminal"
            keystroke "w" using {command down}
        end tell
    end tell
end closeTabOne
于 2014-12-13T03:06:41.520 回答
3

一种方法是这样的:

osascript \
    -e "tell application \"Terminal\"" \
    -e "do script \"exit\" in tab 1 of front window" \
    -e "end tell" > /dev/null

但是必须将终端配置为在 shell 退出时关闭窗口。

任何人都有不需要这样做的解决方案?

于 2014-12-13T00:10:57.373 回答
2

这将仅关闭活动选项卡:

tell application "Terminal" to close (get window 1)
于 2019-08-08T15:14:34.753 回答
0

要确定选项卡的窗口,您可以解析尝试访问选项卡仍然不存在的窗口属性时收到的错误消息。错误消息通常包含窗口的 id,您可以使用它来引用窗口。

由于您的问题已有 5 年历史,因此我将使用可以在脚本编辑器中运行的示例代码而不是难以阅读的 bash 脚本来完成我的回答。

tell application "Terminal"

    -- Perform command
    set theTab to do script "echo 'Hello World'"

    try

        -- Try to get the tab's window (this should fail)
        set theWindow to window of theTab

    on error eMsg number eNum

        if eNum = -1728 then

            (*
                The error message should look like this:
                Terminal got an error: Can’t get window of tab 1 of window id 6270.
            *)

            -- Specify the expected text that comes before the window id 
            set windowIdPrefix to "window id "

            -- Find the position of the window id
            set windowIdPosition to (offset of windowIdPrefix in eMsg) + (length of windowIdPrefix)

            -- Get the window id (omitting the period and everything else after)
            set windowId to (first word of (text windowIdPosition thru -1 of eMsg)) as integer

            -- Store the window object in a variable
            set theWindow to window id windowId

        else

            -- Some other error occurred; raise it
            error eMsg number eNum

        end if

    end try

    close theWindow

end tell
于 2020-02-24T10:12:09.347 回答
0

我认为关键是获取前窗的ID。

tell application "Terminal"
    do script "pwd"
    set myID to id of front window
    close window id myID
end tell
于 2021-10-28T07:01:17.283 回答