Here is a simplified script that always opens a new tab (like bulljit's script):
try
tell application "Finder"
if number of Finder windows is 0 then
set p to POSIX path of (desktop as alias)
else
set p to POSIX path of (target of Finder window 1 as alias)
end if
end tell
tell application "iTerm"
reopen
tell current terminal
tell (launch session "Default Session")
write text "cd " & quoted form of p
end tell
end tell
activate
end tell
end try
If you want the script to reuse existing tabs, replace the tell current terminal
block with something like this:
tell current session of current terminal
write text "cd " & quoted form of p
end tell
But that won't work if for example the current session is busy or running a less or vim process.
Wrapping the script in a try block makes it fail silently. reopen
opens a new terminal window if there are no visible windows or if only for example the preferences window is open. Finder also has an insertion location
property, which is usually target of Finder window 1
or the desktop. But there is a bug in 10.7 and later where it often refers to some other window than the frontmost window.
Some potential problems with bulljit's script:
- It has a one second delay. I don't know if it's needed for something, but I didn't need any delays when I tested this script.
- If you have set iTerm to open new windows in full screen and there are no open windows, it opens a non-fullscreen window.
- It tells Finder to get the path of
front window
(window 1
), which can be an information window or a preferences window. Finder window 1
would always be a file browser window.
- It changes the directory to
/
if the frontmost Finder window is displaying a view that doesn't have a path (like the Network view).
I prefer just using a function like this though:
cf () {
c "$(osascript -e 'tell application "Finder"
POSIX path of (target of Finder window 1 as alias
end tell)' 2> /dev/null)"
}
1I think this should be the accepted answer. – dhilipsiva – 2013-07-06T14:33:08.100