Tuesday, March 29, 2011

MacOS: How to change terminal directory to finder

To open the current directory in a graphical user window (finder) on Mac, from a terminal you simply use the command "open ."  (replace '.' with whatever directory name or file you want).   Mac will then use the default program (the finder) to open the target.  [Note: in windows, you can do a similar thing from the command shell,  cmd, with "explorer ."]

But how do you do the complementary operation - change directories of your terminal to the finder location?

Put this in your ~/.bash_login  file, and then you can  use "cdf" to change terminal directory to the last finder which had focus:

# cdf: cd's to frontmost window of Finder
cdf ()
{
    currFolderPath=$( /usr/bin/osascript <<"    EOT"
        tell application "Finder"
            try
                set currFolder to (folder of the front window as alias)
            on error
                set currFolder to (path to desktop folder as alias)
            end try
            POSIX path of currFolder
        end tell
    EOT
    )
    # ignore the cd if it's my desktop
    if [ "$currFolderPath" != "$HOME/Desktop/" ]
    then
        echo "cd to \"$currFolderPath\""
        cd "$currFolderPath"
    else
        echo "no finder path to cd to..."
    fi
}

One final piece to round this out:   to open a terminal in the current window, you can add "Go2Shell" to your finder - see http://zipzapmac.blogspot.com/2013/07/go2shell-instant-terminal-window.html for more info.

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner

Followers

google analytics