Nicholas Adamou
Nicholas Adamou

Reputation: 741

How to close a terminal window using Apple Script

Background

I am using a combination of AppleScript and Bash to create a program that launches a set of commands in Terminal.app then closes that window when it terminates.

terminal.sh:

#!/bin/bash

# Usage:
#     terminal                   Opens the current directory in a new terminal window
#     terminal [PATH]            Open PATH in a new terminal window
#     terminal [CMD]             Open a new terminal window and execute CMD
#     terminal [PATH] [CMD]      Opens a new terminal window @ the PATH and executes CMD
#
# Example:
#     terminal ~/Code/HelloWorld ./setup.sh

[ "$(uname -s)" != "Darwin" ] && {
    echo 'Mac OS Only'
    return
}

function terminal() {
    local cmd=""
    local wd="$PWD"
    local args="$*"

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    if [ -d "$1" ]; then
        wd="$1"
        args="${*:2}"
    fi

    if [ -n "$args" ]; then
        cmd="$args"
    fi

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    osascript <<EOF
tell application "Terminal"
    activate
    tell window 1
        do script "cd $wd ; $cmd"
        repeat while busy
            delay 1
        end repeat
        my close()
    end tell
end tell

on close()
    activate application "Terminal"
    delay 0.5
    tell application "System Events"
        tell process "Terminal"
            keystroke "w" using {command down}
        end tell
    end tell
end close
EOF
}

terminal "$@"

Issue

Currently, the AppleScript does not close the window when the script itself completes.

Upvotes: 1

Views: 1901

Answers (1)

user3439894
user3439894

Reputation: 7555

I copied and pasted your code into an empty file, saved it and made it executable.

I then ran it in Terminal and received the following error:

 175:183: syntax error: A command name can’t go after this “my”. (-2740)

I then changed the name of the close() handler to closeWindow() and the script worked as desired.

Note that close is a built-in AppleScript command and cannot be used as the name of a handler

Upvotes: 1

Related Questions