How to close a Terminal tab using AppleScript?

瘦欲@ 提交于 2019-12-12 12:18:16

问题


I'm using AppleScript to open PostgreSQL in a Terminal tab like this:

#!/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"

Running this script from the Terminal will open a new tab with PostgreSQL server inside. So at the end of the execution I'll have 2 tabs: the first one which was used to run the script, and the second one containing the server.

How can I close the first one?

This is my try:

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

But I get this error message:

execution error: Terminal got an error: tab 1 of window 1 doesn’t understand the “close” message. (-1708)


回答1:


You can try something like this:

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:


One way to do it is like this:

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

But Terminal must be configured to close the window when the shell exits.

Anyone has a solution which does not need to do this?




回答3:


This will close the active tab only:

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


来源:https://stackoverflow.com/questions/27453987/how-to-close-a-terminal-tab-using-applescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!