Journal of a Maker

Icon

a blog by Warren C. Moore

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:

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.

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.

Category: Mac OS X, Unix

Tagged:

  • Awesome, many thanks! It works perfectly so far, and it's a lot faster than the AppleScript solutions I've seen floating around.
  • Glad to help. This is one of those "notes to self" that I thought might be useful to other folks.
blog comments powered by Disqus

A Brief Note

Journal of a Maker is an eclectic collection of thoughts by Warren Moore, an Atlanta web professional. Some content may be highly flammable. And also nerdy.

Page Index