Journal of a Maker

A technical and personal blog by Warren C. Moore, iOS Developer

Make Terminal Follow Aliases Like Symlinks

Okay, so you’re spelunking around in Mac OS using Terminal. You try to ‘cd’ into a directory only to be told that what you’re trying to get to “is not a directory.” Then you remember that the target directory is actually a shortcut that you created with Finder. It looks just link a symlink in Finder, so shouldn’t it act like one in Terminal?

_ _

Unfortunately, in OS X, aliases are treated differently by the command line than symlinks. In particular, they won’t be followed by the “cd” command, leading to your present frustration. Fortunately, with a little elbow grease, you can patch up your shell and be on your merry way.

This is a two-part process requiring a little familiarity with gcc and bash, but I’ll try to make it as simple as possible. Firstly, you need this file: getTrueName.c. This file was created by Thos Davis and is licensed under the GPLv2. Save it anywhere, then compile it with the following command:

1
gcc -o getTrueName -framework Carbon getTrueName.c

This will create the ‘getTrueName’ executable in the same directory as the source. You can add it to your PATH, or just copy it directly to /usr/bin so it’s easy to access.

Interestingly, when Terminal opens a new shell, .bashrc is not executed as you might expect. Instead, under the login shell, .bash_profile is executed. So, add the following to .bash_profile in your Home directory. You might need to create it first; it isn’t there by default.

1
2
3
4
5
6
7
8
9
10
11
12
13
function cd
{
  if [ ${#1} == 0 ]; then 
    builtin cd 
  elif [ -d "${1}" ]; then 
    builtin cd "${1}"
  elif [[ -f "${1}" || -L "${1}" ]]; then 
    path=$(getTrueName "$1")
    builtin cd "$path"
  else 
    builtin cd "${1}"
  fi
}

Effectively, this looks for Finder aliases and resolves them before deferring to the builtin cd command. Append it to your .bash_profile, then either execute it or restart Terminal for the changes to take effect. Now you can cd to Finder aliases within Terminal and have them treated just like symlinks. Just like it should be.