Skip to content

Learning the Terminal on the Mac - Part 4 - Bringing Finder and Terminal Together

The first few articles laid out a good foundation of basic shell usage, but little Mac-specific information. In this article, all that will change. We’re going to show a few ways to get back and forth between Terminal and Finder.

From Finder to Terminal

There a few methods to get information from Finder into the Terminal, or use Finder in Terminal-like ways.

Path Bar

One new feature in the 10.5 Finder is Path Bar. The Path Bar makes it easy to see the full path to the current folder. To enable the Path Bar (if you haven’t already), activate Finder, and choose View → Show Path Bar from the menu.

lt2-show-path-bar.png

Once enabled, the Path Bar will appear at the bottom of all your Finder windows, just above the Status Bar. Below is how the Path Bar appears when I have my Home folder open in Finder.

lt2-path-bar.png

The the above path would be interpreted as /Users/demo in the shell.

lt4-ls-path-bar.png

Go to Folder…

Finder also has a built in command called Go to Folder… that allows a path to be entered in a similar way as in the shell. This feature can be accessed by choosing Go → Go to Folder… from the menu, but it’s faster to use the shortcut ⌘⇧G.

lt2-go-to-folder.png

The path entry field of the Go to Folder… feature also has rudimentary tab-completion support. If you type a few letters and either press the tab key (⇥) or just wait a few seconds, it will complete the current path component with the first match it finds. It’s not nearly as good as the completion in bash, but it’s there.

Drag & Drop Paths

Files or folders in Finder can also be dragged and dropped directly onto Terminal. Doing so will insert the path to the file or folder into the shell.

lt4-drag-drop-path1.png

And voilà, the path is inserted into the shell:

lt4-drag-drop-path2.png

OpenTerminalHere

OpenTerminalHere is a small Applescript application that launches Terminal and automatically cd’s to the current folder in Finder. It was originally written by Marc Liyanage and has since been updated to make it more Leopard-friendly. I find it extremely handy, and if you think you would too, go here for the download and setup instructions.

OpenTerminalHere is meant to be installed into Finder’s toolbar. This is done by simply dragging the OpenTerminalHere icon to Finder’s toolbar and pausing a few seconds until a small green “plus” indicator appears next to the mouse pointer. If you want to tweak the position of OpenTerminalHere or add spacing, choose View → Customize Toolbar… in Finder’s menu after installing.

lt4-install-openterminalhere.png

Now just click on the OpenTerminalHere icon in the Finder window’s toolbar, and a Terminal will launch and cd to the current folder.

From Terminal to Finder

Even though the shell is a powerful tool, sometimes you may want to switch back to Finder to finish a task. Here are a couple tools to do just that.

open

We’ve used the open command (man page) a few times already to open files with their default application and folders in Finder. This command is actually specific to Mac OS and is not found in other Unix-like operating systems. The open command also allows you to choose the application with which to open the file, or open the file in the default text editor.

To open a file using a specific application, use the -a option:


open -a [application] [file]

For example, if I wanted to open a file called “hello.txt” in MacVim instead of the default editor, TextEdit, I would type:


open -a /Applications/MacVim.app hello.txt

Also as we mentioned just sentences ago, you can use the open command to open a file using the default text editor. This is done with the -t option.


open -t [file]

Let’s say I’m a curious individual, and I want to see exactly what iTunes stores in its XML library file. I would type:


open -t ~/Music/iTunes/iTunes\ Music\ Library.xml

(Remember those extra \’s are to escape the spaces, which was discussed in the second article.

Revealing Files in Finder

The open command can be used to open folders in Finder, but we don’t have a way to reveal a file within a folder. Many applications have a built-in “Show in Finder” feature, but unfortunately the shell does not. However, all hope is not lost.

One of the simplest ways to add new commands in the shell is through creating shell scripts. Shell scripting is a deep topic in itself, but for know, just think of a shell script as a small program that is interpreted by the shell itself. Shell scripts are written in plain text so they are quick to create and easy to modify.

A hint entitled “Select files in Finder from Terminal” on Mac OS X Hints presents a way add a “Show in Finder” feature to the shell using a custom shell script. Several others submitted improvements and alternative approaches in the comments. The solution I liked best is described in this comment by caesurae.

I liked this solution because it was relatively concise and easy to read (for the bash-literate), and it is contained within a single file. I modified the script very slightly to fix a problem with revealing directories.

Here is the full script. Immediately following is a download link, which is probably more useful. Following that, and even more useful still are installation instructions.

The Script

#!/bin/bash
#
# revealInFinder.bash
#
# 05.26.2006
#
# caesurae@gmail.com
#
# tested on Mac OS X 10.3.9 build 7W98 - Darwin 7.9.0 - AppleScript 1.9.3
#
# reveal the given file(s) and/or folder(s) in a Finder window
#
# usage: revealInFinder.bash ~/dir/file "/dir/dir/my file" file
#
########
#
# 08.07.2008
#
# Andy Mroczkowski
#
# minor update to allow for more reliable opening of directories
#
# tested on Mac OS X 10.5.4 - AppleScript 2.0.1k
#
##

# if no arguments are given, echo the usage string
if [ $# -lt 1 ]; then
  echo 'Usage: '`basename "$0"`' [files]' >&2
  exit 1
fi

# define $n, gets +1 for each argument given
# not sure if $n is needed, how to get index number of $1, $2, etc.?
n=0

# define $act, gets +1 for each argument that passes test
act=0

# step thru each argument one at a time
for thearg in "$@"; do

  n=$(( n + 1 )) 

  # if $thearg exists then
  if [ -e "$thearg" ]; then

    # get the absolute path to the argument
    thearg="`cd \`dirname \"$thearg\"\`; pwd`/`basename \"$thearg\"`"

    # create a applescript statement using $thearg for osascript to execute
    osatext='tell application "Finder" to reveal POSIX file "'"$thearg"'"'
    /usr/bin/osascript -e "$osatext"

    # $act activates Finder after processing the remaining arguments
    act=$(( act + 1 )) 

  # else if $thearg does not exist then
  else

    # if $thearg is not the last argument given then
    if [ $n -lt $# ]; then

      # ask to continue processing the remaining arguments
      echo -n '"'"$thearg"'" does not exist and will be ignored. continue?  (y/n)? ' >&2
      read ans
      case $ans in
        "n" ) exit 1 ;;
        "y" ) continue ;;
      esac

    # else if $thearg is the last arguement then
    else

      # print the "does not exist" string and exit
      echo '"'"$thearg"'" does not exist.' >&2

      # exit status 1 indicates an error occurred
      exit 1
    fi
  fi
done

# if $act is greater than 0 then activate the finder
if [ $act -gt 0 ]; then
  /usr/bin/osascript -e 'tell application "Finder" to activate'
fi

# exit status 0 indicates all is ok
exit 0

Download the reveal script (and unzip it if necessary).

Installation

Once you have reveal downloaded, you need to put it a place where the shell can find it. Executable files are usually kept in a directory called “bin“. To avoid any permissions problems, we’re just going to set up this script for the current user. To create a bin directory for yourself, type:


mkdir ~/bin

Now the reveal script must be moved into the bin directory. If you saved reveal in your Downlaods folder, you would type the following:


mv ~/Downloads/reveal ~/bin

Of course if you saved reveal to some place other than your Downloads folder, you’ll have use the appropriate path.

Finally we need to ensure that reveal is executable. If you downloaded it from the using the link above, the permissions should have been preserved within the zip file, but we’ll reset them just in case. Changing basic permissions from the command line is done with chmod (man page). We’ll go into detail on chmod later. For now just type


chmod +x ~/bin/reveal

Ok, now everything is in place, but there is still one more thing left to do. The shell only looks in a few pre-defined places for programs and although a ~/bin directory is common, it does not search that directory by default. We can tell the shell to look for programs in our ~/bin directory by adding it to our PATH.

The PATH variable controls where the shell looks for programs. You can manually type in the command to add ~/bin to our PATH, but the PATH variable is cleared every time we open a new shell. That’s a hassle. Instead we want it so our PATH is set up for us automatically. To do that, we will add the command to a special file called .bash_profile which is loaded every time a new shell is started.

First, create the file. The file must be in your home directory (~) or the shell won’t find it. If you already have a .bash_profile the following command won’t overwrite it.


touch ~/.bash_profile

Now open the new, empty .bash_profile file in your default text editor:


open -t ~/.bash_profile

Next add the following line exactly as it appears below. Copy and Paste are your friends. If you already have some stuff in your .bash_profile just add it to the end.


export PATH=$PATH:$HOME/bin

Save and close the file. Then close the Terminal you were working in and open a new one (your .bash_profile is only read when the shell starts up).

Congratulations, you now have installed a shell script. Have a beer.

Usage

Our new reveal script is easy to use. You just type reveal followed by one or more paths to files or directories. In fact, if you type reveal with no arguments, it prints a helpful usage statement:


Usage: /Users/demo/bin/reveal ~/dir/file "/dir/dir/my file" file

Of course since we went through all the trouble of putting reveal into our path, we can just type:


reveal ~/dir/file "/dir/dir/my file" file

Here it is in action:

lt4-reveal-in-action.png

Wrap-up

So there we have it - Terminal and Finder peacefully co-existing. What a wonderful world. If you have more suggestions about integrating these fine pieces of software, or a question, feel free to comment. Feedback is always welcome.

One Comment

  1. taranaki

    I OpenTerminalHere, as well as ‘open .’ Thanks for the pointers. You mroc!

    Posted on 12-Aug-08 at 2:33 pm | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*