Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a Terminal tab using AppleScript?

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)

like image 342
David Morales Avatar asked Jan 10 '23 06:01

David Morales


2 Answers

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
like image 112
adayzdone Avatar answered Jan 11 '23 20:01

adayzdone


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?

like image 39
David Morales Avatar answered Jan 11 '23 18:01

David Morales