How to close terminal window launched using Apple Script in Mac app

I have a Mac application.

This app is executing following apple script using executeAndReturnError method of NSAppleScript class:


set tempDir to path to temporary items as string

set tempFilename to tempDir & "Test_Log.txt"

set tempFilePath to POSIX path of file tempFilename

set wasRunning to application "Terminal"'s running

tell application "Terminal"

if not wasRunning then

close front window saving no

end if

set mytab to do script "ls -l" & quoted form of tempFilePath

set title displays custom title of current settings of mytab to true

set custom title of current settings of mytab to "Test Log"

repeat until busy of mytab is false

delay 1

end repeat


if ((count of windows) = 1) then

quit

else

close (every window whose name contains "Test Log")

end if

end tell


When above apple script is executed by my app for the first time, terminal window remains open.

When above apple script gets executed subsequently, terminal window is closed (as expected).


Can anyone please assist me on how can I close the terminal window always.


Please note that, I want to close the terminal window that has been opened by my apple script mentioned above.

If there is already other terminal window opened (manually by user) before running above apple script, it should not be closed.

Replies

Does this script work if you run it from Script Editor?

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Why are you doing that to being with? Don't try to use AppleScript to interact with the Terminal from an app. That is simply never, ever going to work for multiple reasons. Just get the data directly and display it within your app.

I think your problem is the test on "count of windows". If the only window open is your Terminal window with name of "Test Log," the test still succeeds and you don't close the window. You might want to test against 0.