Close Unwanted Mac Terminal Windows En-masse - macos

As a system admin, I write/test/run a ton of shell scripts (typically from BBEdit). I rely on the BBEdit “Run in Terminal” drop-down menu a lot to quickly test run a script.
As a result, I end up with a ton of 'dead' (unwanted/expired) Terminal windows (i.e. executed script windows with “[Process completed]" displayed at the bottom).
Does anyone have a suggestion for how to clean-up all of these dead Terminal windows em-masse?
I can't blindly close ALL windows (or quit Teminal.app) because I have current SSH sessions running and other tasks in-progress. I only want to close the Terminal windows that have been executed via BBEdit and display '“[Process completed]'.
I can't set the Apple Terminal.app preference to do this for me (Terminal -> Preferences -> Settings -> Shell -> When the shell exits) because I generally want to examine the output returned before closing for QA purposes.
My goal is to manually run a script/command from time to time to clean-up all the Terminal windows on-demand as needed. Once I have a ton of confusing dead windows that I dont need Ill run it and then continue working in BBEdit as needed.
After a few hours of writing/troubleshooting/editing a script (or multiple scripts) I end up with dozens of dead Terminal windows - of which I manually close with a click and a Command + W. This gets tedious of course.
I have played around in AppleScript for something to bind to a shortcut or widget, but haven't found a solution as of yet.
Simple commands such as
tell application "Terminal" to close (get window 1)
aren't too helpful because I havent been able to determine which windows have an inactive state and which do not.
Thoughts? Any suggestions are appreciated!

Every "window" object in Terminal has a property named "processes", which is a list of the active processes for that window.
If the "processes" list is empty (in AppleScript terms, processes = {}), then you can safely close the window.
Therefore, an AppleScript like this should work:
tell application "Terminal"
set windowsICanClose to (every window whose processes = {})
repeat with windowToClose in windowsICanClose
close windowToClose
end repeat
end tell
You can save that as a script, put it in BBEdit's "Scripts" folder, assign it a keyboard equivalent if you like, and that should do the job.

It's very simple:
tell application "Terminal" to close (every window whose processes = {})
This will close every window of Terminal that has: [Process completed]
Just to be clear.. If e.g. you have a Terminal window open with multiple tabs, then tell application "Terminal" to close (every window whose processes = {}) only closes the tabs that have [Process completed] and not any other tab in that window. The window is only closed if the only tab of that window contains [Process completed]. That is to say, that is the result as tested under macOS High Sierra anyway.

Related

applescript: how to terminate an executing terminal

I'm trying to make an apple script to allow me to manage a cpp project automatically. And I used Jenkins too.
Basically, the cpp project is a kind of infinite loop, which will execute in a terminal. And I set Jenkins rebuild and execute it per 20 sec. In other words, my pc should do the tasks below:
1) rebuild the project;
2) execute the project;
3) wait for 20 sec;
4) close the terminal.
However, when I arrive at 4), a dialog will pop up: Do you want to close this window?
So I have to click the button "Close".
My question is: how to code in applescript to do the 4) automatically?
Here is my applescript:
tell application "Terminal"
do script "cd /Users/Shared/Jenkins/Home/workspace/test"
do script "make clean" in window 1
do script "make" in window 1
do script "./matrix.out" in window 1
delay 20
close window 1 # problem's here
end tell
However, when I arrive at 4), a dialog will pop up: Do you want to close this window? So I have to click the button "Close".
But you can do that using AppleScript too (via GUI scripting thru System Events), so nothing you've said is a problem so far.
tell application "Terminal" to activate
tell application "System Events"
tell application process "Terminal"
tell its window 1
tell its sheet 1
click button "Close"
end tell
end tell
end tell
end tell
I wonder if this might help:
Running process in background after closing terminal
The problem might be that what you're lastly running in the terminal is a process (matrix.out) that will get killed by closing the window, and you don't want that, right? So it may be that you need to alter the matrix.out script using the technique described (if possible) to keep it from doing that.
It may also be possible to solve your problem by making matrix.out executable (chmod it to executable or use Kilometre) and just "open it" using vanilla applescript.

Running Applescript: WorkFlowServiceRunner will not terminate

I am trying to make a keyboard shortcut to launch terminal in OS X Mountain Lion.
After some research I found out that I can use Automator to achieve this:
http://mac.tutsplus.com/tutorials/tips-shortcuts/how-to-launch-any-app-with-a-keyboard-shortcut/
It works, but I noticed that whenever I launch a terminal using this method, a process called WorkFlowServiceRunner starts and never terminates. To make matters worse when I launch more terminals (or launch different applications using shortcuts, again, through Automator) multiple WorkFlowServiceRunner processes start and quickly eat up the memory.
I've also tried writing my own applescripts but the problem does not go away. This clearly looks like a memory leak. Is this a bug in OS X Automator? Is there a way to write an applescript so that the WorkFlowServiceRunner terminates after doing its job (e.g. launch a terminal)? Automator seems to be the most "native" way of getting this done and I do not want to use any 3rd party apps.
I have noticed this from time to time.
One way around it would be to make your own service apps with a Cocoa-AppleScript Applet.
It is not very hard to do. And I will try and guide you through it. It should only take you a couple of minutes.
Step 1.
Open your Application Applescript Editor. And go to the "File" Menu -> "New from Template" -> Cocoa-AppleScript Applet.app
Step 2,
Paste this code into the new documents.
property NSWorkspace : class "NSWorkspace"
tell current application's NSApp to setServicesProvider_(me)
NSUpdateDynamicServices()
my runAService()
on runAService()
NSWorkspace's sharedWorkspace()'s launchAppWithBundleIdentifier_options_additionalEventParamDescriptor_launchIdentifier_("com.apple.Terminal", current application's NSWorkspaceLaunchDefault, missing value, missing value)
tell me to quit
end runAService
Step 3,
Compile
(click this to compile)
and Save the app.
*Make sure the show startup screen is unchecked in the Save dialogue.
Giving the app a name like LaunchTerminal.app
Step 4,
Click the "Bundle Contents" button on the top right hand side of the document.
This will open the applications contents view.
Click the Action button and then "Reveal in finder" sub menu.
step 5,
In the contents folder that opens in the finder you will see a file name "info.plist"
Open Terminal.app and type and run this code using the path to this file:
BUT make sure you do not include the ".plist" part of the name when entering it in Terminal.app
/usr/bin/defaults write /Users/YourUserNameHere/myServiceApps/LaunchTerminal.app/Contents/Info NSServices -array-add '{NSMenuItem={default="Launch Terminal";}; NSMessage="runAService"; NSSendTypes=();}'
( You can drag n drop the file into terminal to get the posix path string )
The path part looks like this: /Users/YourUserNameHere/myServiceApps/LaunchTerminal.app/Contents/Info
This code should add an array to the plist file which is part of the apps way of broadcasting it has a service.
step 6,
Compile and Save the App again.
Just to make sure it picks up the changes. ( I found I had to do this even though I should not have to)
step 7,
Double click the app to run it for the first time.
The App will quit straight away. But the first run should have broadcast that it has a service that should be registered with the system
step 8,
Open system Preferences and go to Services -> General (section)
And you will see the "Launch Terminal" service.
Set up your short cut as normal.
Hope this helps..
UPDATE :
I noticed that the tell application "Terminal" to activate. Would not open my default Window groups if I had closed them all and quit Terminal before. The normal behaviour if I have done this is for my default window group to open. ( I have two Tabs open at startup each cd'd to a different path).
So I have change the open application to a cocoa way of doing it.
A do shell script with open the/application/path/. will work also.
Try using Butler or QuicKeys. They both have endless "Trial periods."

Google SketchUp close file

The Ruby API to Google SketchUp has a function, open_file, but I can't find a close_file function. Since I have to batch process many files, I want to close each file before moving on to the next, otherwise the program will crash from memory exhaustion.
What is the best way to close SketchUp files programmatically?
I am using Mac OS X and am willing to use AppleScript functions to signal the window to close.
EDIT
I am considering a few approaches that have proven fruitless so far.
Using the appscript Ruby gem, as described in this question. The problem here is that I cannot get SketchUp to recognize my installed gems.
In a similar vein, I am trying to use osascript (a bash program that executes AppleScripts from the shell) to close the window. That is, I call out to the shell from SketchUp's Ruby console window using one of the following:
%x[osascript -e 'tell application "SketchUp" to close window 1']
%x[osascript -e 'tell application "SketchUp" to close window 1' &]
%x[osascript -e 'tell application "SketchUp" to close every window']
%x[osascript -e 'tell application "SketchUp" to close every window' &]
Whenever I try this second approach, SketchUp just freezes. However, when I execute any of these commands from an IRB or directly from the Bash prompt outside of SketchUp, I get the desired behavior: the model window closes (incidentally, the Ruby console window remains open, which is fine).
Have a master script that launches a slave script to process each model. The slave will run within the Google SketchUp program while the master waits. When the slave is finished, it signals the master, and the master closes the SketchUp file. To do this interprocess communication, I tried using drb. However, when I try to require drb within SketchUp, I get the following message:
Error: LoadError: (eval):5:in 'require': no such file to load -- drb
EDIT 2
Having a separate process continuously running that closes Google Sketchup windows using AppleScript when signaled is clumsy for a number of reasons. First, it's ugly to have to have a separate process devoted to closing Sketchup windows. Second, the only effective way of communicating with the external script is through the creation of files, which is wasteful and the disk access may be slowing things down.
However, the most severe issue is that Sketchup is slow at responding to AppleScript commands. I have a pretty computation intensive script running in Sketchup, and it seems to starve the AppleScript response, which means that the osascript times out before the windows close. Sketchup only gets around to responding to AppleScript when there is a dialogue box prompt in Sketchup that pauses the execution of my computationally intensive script.
EDIT 3
I have modified my close_file function to pause execution of the script by displaying a dialog box. This essentially yields the current thread and allows the thread that responds to AppleScript commands to execute:
def close_file()
f = '/temp/mutex.txt' # for finer control, use different mutex for each window you want closed
File.new(f, 'w').close
result = UI.messagebox "Click OK when window has closed."
end
Then the separate ruby script that closes windows via AppleScript will additionally have to click "OK" in the dialog box. AppleScript to do that is:
tell application "System Events"
tell process "SketchUp"
set frontmost to true
keystroke return
end tell
end tell
This modification is an improvement. It corrects the "most severe issue" mentioned in EDIT 2, but the other issues remain.
There is an important limitation with using an external AppleScript to force SketchUp to do something. SketchUp will not accept any user input while a menu script is running.
I found this out trying to setup an automated rendering solution. I added a menu item which opens a WebDialog to get a list of models to download from a server. It then steps through the list and uses cURL to download each model. Once downloaded it loads the model, renders it out, uploads the images using cURL again, and goes to the next model.
What I wanted was to activate the AppleScript after each model is rendered (using the "mutex" file solution shown above) and have it close the model window. Unfortunately, since the menu script is still running, SketchUp will not respond to anything the AppleScript tells it to do. Only once all of the models have been processed and the menu script exits, will the AppleScript finally run.
This would not be so bad if all of the calls to the AppleScript were queued up, but they aren't. It seems that only the last two get honored (that number may be just an accident dependent on the timing of when my calls to the AppleScript were made relative to when the menu script finished).
Because of this limitation, I was not able to use the mutex wait() function in my menu Ruby code. Since the AppleScript was not able to execute, it never created its "I'm done" mutex file, and therefore the wait() function in Ruby never got the signal that it could continue. The result was a deadlock between AppleScript and SketchUp, such that SketchUp just freezes up (well, actually it is just stuck in a really tight loop in the wait() function).
So, when approaching this problem, think of AppleScript as a cleanup tool you can call when all of your processing is done.
One solution is to have a separate process continuously running that will close Google Sketchup windows using AppleScript when signaled. The approach described here uses files to do the interprocess communication (drb did not seem to work).
First, you have to make sure Sketchup supports AppleScripting. To do this, execute the following at the command prompt (with appropriate substitutions for different Sketchup versions, etc.):
$ defaults write /Applications/Google\ SketchUp\ 8/SketchUp.app/Contents/Info NSAppleScriptEnabled -bool YES
Now, create a separate file that will close Sketchup windows. Here is my closer.rb file:
#!/usr/bin/ruby
## closer.rb ##
def wait(f)
while !File::exists?(f)
end
File.delete(f)
end
def signal(f)
File.new(f, 'w').close
end
while true
wait('~/temp/mutex.txt')
msg = %x[osascript -e 'tell application "SketchUp" to close every window']
signal('~/temp/conf.txt')
end
Run this script from the shell. It waits until the file ~/temp/mutex.txt is created. Once the file is created, it runs osascript (essentially AppleScript) to close all the windows in Sketchup, and then signals that the windows were closed by creating a ~/temp/conf.txt file.
Here is the client code (which can be placed in your Sketchup plugins) that signals the closer script:
def wait(f)
while !File::exists?(f)
end
File.delete(f)
end
def signal(f)
File.new(f, 'w').close
end
def close_file
signal('~/temp/mutex.txt')
wait('~/temp/conf.txt')
end
The close_file signals the closer script and then waits for a confirmation that the file was closed before returning. Now you can close files in Sketchup.
You can do a lot with SketchUp using applescript and/or Automator.
tell application "SketchUp"
activate
tell application "System Events"
delay 1.0 --close window, adjust delay to suit
--key code 13 using command down -- Press ⌘W or you can use
keystroke "w" using command down
end tell
end tell
I have a number of status bar items for open new, paste to console, closing, killing SU etc.
They're tiny files that trigger the SU shortcut keys, and can be used externally, from 'Ruby Console' or as part of a plugin.
I'm not sure what kind of 'batch convert' your trying to achieve, but
I used Automator to convert most of my old v5, V6, v7 files to v8 today...
100's of them,
and your probably aware, on opening you get 'alert' warning that saving will convert the file to the latest version (which is what I wanted).
It's tricky to click this "OK" programatically.
Automator on it's own is quite restricted, but you can add an applescript to the workflow and I've found that if you use it's 'record function' to demonstrate what you need to do.
You can then copy/paste that code into 'Script Editor', get rid of the 'dowithTimeout' bits, copy it back into the workflow with delays either side and let it run.
I had to play around with delays, to accommodate some larger files, but achieved >95% success. [Success being able to select all, right click, Create Icon and Preview.]
Unfortunately I then binned the workflow, but could recreate it, if you want to have a look.
success, in Ruby Console
system("osascript -e 'tell application \"suoff\"' -e 'activate' -e 'end tell'")
and this script inside an Automator.app in applications folder....
on run
-- Make sure SU is foremost, don't click on anything else either
tell application "System Events"
tell process "SketchUp"
set frontmost to true
-- gives a message if you try to select when SU's not running
delay 0.2
tell application "SketchUp" to quit saving no
-- no dialog box etc...
delay 0.1
end tell
end tell
end run
the problem is SU has an anti self destruct ruby, that mines any linked files and aborts all efforts to shut it down... from inside itself.
so you need to bury it...
this combination works on 10.5.8 with SU8.1.
if you have a look at SketchUcation [Developer] Forum, I left a call for mac/applescript testers... I've rewritten the app since then but if you PM me I'll send you an open copy of all the bits I've got working..
john
I had to convert hundreds of .skp files with a batch processing script. I faced similar issue, since every time I opened a new file it remained opened. For me it was enough to close the active_model and the file goes with it.
This was true for SketchUp 2019 Pro Mac OS X version.
model = Sketchup.active_model
model.save(filename, Sketchup::Model::VERSION_2015)
model.close
Hope it will help

In OSX can I use a system call to pass a command to a running terminal in a new tab?

Specifically,
In OSX 10.6 from a system call, I want to open a file for editing with VIM in a preexisting terminal (i.e. Terminal.app) by opening a new tab.
Of course I can open a new instance of terminal
/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal -e vim MyFile
And, of course I can figure out the PID of the running instance of Terminal but I don't know how to pass a command into that running program. Or, if Terminal supports receiving commands and if it will open a new tab.
If someone knows how to do this with a similar system (e.g. linux and xterm) it could help me figure it out with OSX and Terminal - or, is there some other technique to prevent opening so many terminals instances?
EDIT: CHEAP SOLUTION
I created an AppleAcript script
on run app_arg
tell application "System Events"
tell application process "Terminal"
key code {55, 36}
set frontmost to true
key code {55, 17}
keystroke item 1 of app_arg
keystroke return
end tell
end tell
end run
and run it via the system call like so
/usr/bin/osascript NEWSCRIPT.scpt "args"
It's dirty but it gets the job done - thanks!
The way to accomplish the is with applescript. You can send applescript to things in OS X with the osascript command. I wasn't able to find anything quickly that directly shows how to open a new tab with a command running in it, but I was able to find a couple of references to automating Terminal.app in various other ways with applescript, and I think they may point you in the right direction.
Various random Terminal.app applescript hacks mostly centered around changing colors.
An applescript hack that opens a new terminal window without creating a new Terminal process.
A nice StackOverflow question about how to query an application to discover what applescript it supports (stolen from a comment on your question by #dmckee)
And this nice StackOverflow question concerning Terminal.app's applescript specifically (again stolen from a comment by #dmckee)
An even better exploration of the Leopard Terminal.app's applescript from Ruby no less
And from that last link, it looks like the only way to do it is to use applescript to send the Command-T keystroke to the terminal. That's ugly, but it'll work. And then you can send the command you want to execute. :-)
There are three ways to do this:
Use popen
Use system
Use exec family

Open terminal here in Mac OS finder [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Closed 10 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Is there something similar to the "Open Command Window Here" Windows Powertoy for Mac OS? I've found a couple plugins through a google search but wanted to see what works best for developers out there.
As of Mac OS X Lion 10.7, Terminal includes exactly this functionality as a Service. As with most Services, these are disabled by default, so you'll need to enable this to make it appear in the Services menu.
System Preferences > Keyboard > Shortcuts > Services
Enable New Terminal at Folder. There's also New Terminal Tab at Folder, which will create a tab in the frontmost Terminal window (if any, else it will create a new window). These Services work in all applications, not just Finder, and they operate on folders as well as absolute pathnames selected in text.
You can even assign command keys to them.
Services appear in the Services submenu of each application menu, and within the contextual menu (Control-Click or Right-Click on a folder or pathname).
The New Terminal at Folder service will become active when you select a folder in Finder. You cannot simply have the folder open and run the service "in place". Go back to the parent folder, select the relevant folder, then activate the service via the Services menu or context menu.
In addition, Lion Terminal will open a new terminal window if you drag a folder (or pathname) onto the Terminal application icon, and you can also drag to the tab bar of an existing window to create a new tab.
Finally, if you drag a folder or pathname onto a tab (in the tab bar) and the foreground process is the shell, it will automatically execute a "cd" command. (Dragging into the terminal view within the tab merely inserts the pathname on its own, as in older versions of Terminal.)
You can also do this from the command line or a shell script:
open -a Terminal /path/to/folder
This is the command-line equivalent of dragging a folder/pathname onto the Terminal application icon.
On a related note, Lion Terminal also has new Services for looking up man pages: Open man page in Terminal displays the selected man page topic in a new terminal window, and Search man Pages in Terminal performs "apropos" on the selected text. The former also understands man page references ("open(2)"), man page command line arguments ("2 open") and man page URLs ("x-man-page://2/open").
This:
https://github.com/jbtule/cdto#cd-to
It's a small app that you drag into the Finder toolbar, the icon fits in very nicely. It works with Terminal, xterm (under X11), iterm.
An application that I've found indispensible as an alternative is DTerm, which actually opens a mini terminal right in your application. Plus it works with just about everything out there - Finder, XCode, PhotoShop, etc.
Clarification (thanks #vgm64): if you're already in Terminal, this lets you quickly change to the topmost Finder window without leaving Terminal. This way, you can avoid using the mouse.
I've added the following to my .bash_profile so I can type cdff in Terminal at any time.
function ff { osascript -e 'tell application "Finder"'\
-e "if (${1-1} <= (count Finder windows)) then"\
-e "get POSIX path of (target of window ${1-1} as alias)"\
-e 'else' -e 'get POSIX path of (desktop as alias)'\
-e 'end if' -e 'end tell'; };\
function cdff { cd "`ff $#`"; };
This is from this macosxhints.com Terminal hint.
Check out Open Terminal Here. It may be the most similar to "Open Command Window Here." I used >cdto and this is very similar but this seems to be a little better at dealing with Spaces... but not perfect.
What it has that is very nice is the ability to "detect key-down events at the start of the application and used them to modify the behavior of the script" allowing the script to open a new tab in the front most terminal window when invoked by holding down ⌘ key. Neat trick.
Also note PCheese's answer; it is probably more useful for heavy terminal users!
There is an updated version of the very nice and slim Open Terminal Here posted by vgm64 and d0k. The change was made by james david low. He published the new version on his site. Just download OpenTerminalHere.zip, extract it, move the bundle to your Library/Scripts folder and drag it from there to your Finder toolbar.
What is special about it is that it always opens a new tab if a Terminal.app window is already open. Very useful! I also noted that the style of the button of the application better fits the Snow Leopard Finder.app style than cdto posted by redacted did.
Also, you can copy an item from the finder using command-C, jump into the Terminal (e.g. using Spotlight or QuickSilver) type 'cd ' and simply paste with command-v
I created a bundle with 3 apps for the finder toolbar.
The other two apps do:
open Textmate with the current selection
open GitX with the current folder
For more information see here:
http://nslog.de/posts/71
If you install Big Cat Scripts (http://www.ranchero.com/bigcat/) you can add your own contextual menu (right click) items. I don't think it comes with an Open Terminal Here applescript but I use this script (which I don't honestly remember if I wrote myself, or lifted from someone else's example):
on main(filelist)
tell application "Finder"
try
activate
set frontWin to folder of front window as string
set frontWinPath to (get POSIX path of frontWin)
tell application "Terminal"
activate
do script with command "cd \"" & frontWinPath & "\""
end tell
on error error_message
beep
display dialog error_message buttons ¬
{"OK"} default button 1
end try
end tell
end main
Similar scripts can also get you the complete path to a file on right-click, which is even more useful, I find.
It's a bit more than you're asking for, but I recommend Cocoatech's Path Finder for anyone who wishes the Finder had a bit more juice. It includes a toolbar button to open a Terminal window for the current directory, or a retractable pane with a Terminal command line at the bottom of each Finder window. Plus many other features that I now can't live without. Very mature, stable software.
http://cocoatech.com/
Ok, I realize that this is a bit late... maybe this alternative wasn't available at the moment of writing the post?
Anyway, I've found installing the pos package via Fink (a prerequisite in this case, maybe there is something similar for those who uses MacPorts?) to be the easiest solution. You get two commands:
posd - which gives the current directory of the frontmost Finder window (for which you presumably make an alias cdf=cd posd)
fdc - which switches the current directory of the frontmost Finder window to the Terminal pwd. This is slightly different from 'open .' which always opens a new finder window.
Yes, you have to switch to the Terminal window before writing cdf, but I suppose that's quite cheap comparing to clicking a button in the Finder toolbar. And it works with iTerm as well, you don't have to download a separate Finder toolbar button that opens an iTerm window. This is the same approach as proposed by PCheese, but you don't have to clutter your .bash_profile.
If like me you turn off the Finder toolbar, this Service adds an item to every folder's contextual menu: http://blog.leenarts.net/2009/09/03/open-service-here/
This also allows you to open any folder you see in Finder tree view.
I mostly use this function:
cf() {
cd "$(osascript -e 'tell app "Finder" to POSIX path of (insertion location as alias)')"
}
You could also assign a shortcut to a script like the ones below.
Reuse an existing tab or create a new window (Terminal):
tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "Terminal"
if (exists window 1) and not busy of window 1 then
do script "cd " & quoted form of p in window 1
else
do script "cd " & quoted form of p
end if
activate
end tell
Reuse an existing tab or create a new tab (Terminal):
tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "Terminal"
if not (exists window 1) then reopen
activate
if busy of window 1 then
tell application "System Events" to keystroke "t" using command down
end if
do script "cd " & quoted form of p in window 1
end tell
Always create a new tab (iTerm 2):
tell application "Finder" to set p to POSIX path of (insertion location as alias)
tell application "iTerm"
if exists current terminal then
current terminal
else
make new terminal
end if
tell (launch session "Default") of result to write text "cd " & quoted form of p
activate
end tell
The first two scripts have two advantages compared to the services added in 10.7:
They use the folder on the title bar instead of requiring you to select a folder first.
They reuse the frontmost tab if it is not busy, e.g. running a command, displaying a man page, or running emacs.
There is a bug in the AppleScript on OSX 10.6. (2 terminal windows open).
I fixed this by adding the close command after activate. This close the first Terminal window.
on run
tell application "Finder"
try
activate
set frontWin to folder of front window as string
set frontWinPath to (get POSIX path of frontWin)
tell application "Terminal"
activate
close
do script with command "cd \"" & frontWinPath & "\""
end tell
on error error_message
beep
display dialog error_message buttons ¬
{"OK"} default button 1
end try
end tell
end run

Resources