如何使用AppleScript关闭终端选项卡?

时间:2014-12-12 23:59:20

标签: applescript osascript

我使用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 个答案:

答案 0 :(得分:3)

一种方法是这样的:

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

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

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

答案 1 :(得分:3)

您可以尝试这样的事情:

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

答案 2 :(得分:1)

这将仅关闭活动选项卡:

tell application "Terminal" to close (get window 1)

答案 3 :(得分: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