Drag a File to OS X Terminal Window to Get Path, Edit

One of the coolest tricks in OS X is the ability to drag a file from the Finder to the Terminal window to see its path. If the file is editable, you can enter an editor command before you drag the file.

Let's say that you're preparing to edit a text file in the Terminal. Your first thought might be to use the cd shell command to navigate to the file. Then enter something like:

$ vi ./filename.txt

However, one of the cool things about OS X is the integration of the GUI and Unix. If you already have a Fnder window open to a directory (folder) that you’re working in, you can just drag the file icon to the Terminal’s command prompt. For example, let’s say you want to edit the Perl script area.pl. First, on at the terminal prompt, type “vi” (or your favorite editor command), and then just drag the file name over to the cursor. Like this:

Voila!  The icon in the Finder is magically converted to a text path in the Terminal. Then hit return to edit the file.

Also, this string, a Unix path, can be copied right out of the Terminal and pasted somewhere else. That’s handy if you’re writing a paper or article, the path is very long, and you want to copy the exact path without the risk of a typo. In the above example, I just selected and copied the path, and then pasted into this very article I’m writing:

/Users/john/Programming/Perl/area.pl

Of course, there are many ways to see the path to a file in the OS X Finder, but this is a handy way to make it amendable to copy and paste. And if you’re editing a bunch of files with very long (or similar) names on the command line, dragging the icon can be quicker and less error prone than typing the full name on the command line, especially when autocompletion doesn't help much.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.