This also prints an error if the front Finder window is in the computer or network view, exits with 1 on errors, uses local variables, and replaces $HOME with ~.
f() {
local d=$(osascript -e 'try
tell application "Finder" to POSIX path of (target of Finder window 1 as alias)
end')
[ -z "$d" ] && echo "No Finder window found" >&2 && return 1
cd "$d" && echo "${PWD/#$HOME/~}"
}
As @Stuart says you can open the current directory in Terminal by
open .
Hardly long enough to be worth scripting but if you must, use this instead of the "open -a Finder ./".
The problem with `open .` is that if you're inside any kind of bundle (application, document, package, etc.) it will open that instead of Finder. I prefer to specify the application, and I'm not sure why people take such umbrage with that. It's an alias, you're just typing f either way, and my way happens to work in more circumstances. So there.
in zsh you can simplify the cdf script to " cd `osascript -e 'tell application "Finder" to get POSIX path of (target of front Finder window as text)'` " and it works just as well.
If you use it as written it still works, but for the rest of your session the directory will show up as "target" in your prompt.
And if you use oh-my-zsh, all you need to do is enable the osx plugin (which by coincidence also uses the command "cdf") https://github.com/robbyrus... . and you get other nice things like quick-looking files from the command line
I don't know enough about zsh to know why it would substitute a variable name for a directory name, but the point of the $target variable is to allow for error catching after the AS runs. I suppose you could run the AS twice, once to check and once to perform the above, but that's overkill...
Here is a solution that works with zsh, clearing $target fixes the issue.
# cd to the path of the front Finder windowcdf() { target=`osascript -e 'tell application "Finder" to if (count of Finder windows) > 0 then get POSIX path of (target of front Finder window as text)'` if [ "$target" != "" ]; then cd "$target"; target=""; pwd else echo 'No Finder window found' >&2 fi}
I rewrote the script as
cdf() {
appscript='tell application "Finder" to get POSIX path of (target of front Finder window as text)'
cd "$(osascript -e "$appscript")"
}
because I thought it looked more elegant.
It doesn't play very nicely with Mission Control though, unfortunately. Anyone know enough AppleScript to make it go to the last window used, not the frontmost?