Opening Xterm to the path selected in Finder

The following Applescript can be used to open an Xterm to the path selected in the Finder. It is modified from the very useful website of Michael Eichberg.

It can be used very effectively by 1) Opening the AppleScript Editor, entering the text, and saving it as an application, and 2) Dragging the application into the Finder's toolbar. Then you can simply select folders and click the application OpenXterm in the toolbar and an xterm will open to that directory. See Michael's page for detailed pictures of how to do this.

(* Handler that activates the terminal app if necessary,

and executes a "cd" command to switch to the given

folder / path. *)

on openXTerm(quoted_path)

tell application "X11"

activate

end tell

tell application "System Events"

tell process "X11"

tell menu bar 1

tell menu bar item "Applications"

tell menu "Applications"

click menu item "Terminal"

end tell

end tell

end tell

delay 0.5

tell window frontmost

keystroke "cd " & quoted_path

key code 36

end tell

end tell

end tell

(*do script with command "cd " & quoted_path*)

end openXTerm

(* Opens a new terminal window with the current directory

set to the folder selected by the user in the finder. If the

user has selected multiple folders, a new window is opened

for each folder.

If the user has selected a file, the file's containing folder is

used. If multiple files in the same directory are selected,

only one terminal window is opened and the directory is

set to the folder containing the files. *)

tell application "Finder"

set sels to selection

if sels is not {} then

-- set of paths for which we have already opened

-- a terminal window

set opened to {}

repeat with sel in sels

-- convert to an alias to be able to

-- test if the selected item is a folder

set sel to sel as alias

try

-- if this selected item is not a folder an

-- exception is thrown

exists folder sel

on error

set sel to (container of sel)

end try


-- convert the current path to a POSIX

-- (UNIX) path.

set sel to sel as text

set p to POSIX path of sel

-- quote to handle directories with white

-- spaces

set qp to p

set qp to quoted form of p


if opened does not contain qp then

openXTerm(qp) of me

set opened to opened & {qp}

end if

end repeat

else

(display dialog ¬

"You have to select a folder." with title ¬

"Error" with icon stop ¬

buttons {"OK"})

end if

end tell