Enable 'cd' into directory aliases from the Terminal

Sep 01, '05 10:17:00AM

Contributed by: tbdavis

I use the command line often and have been frustrated by the second-class-status that file system aliases have in the command shell. It would be nice if Apple would have the BSD system calls treat aliases the same as soft links, but alas, as of 10.4.2, they have not done so.

Also, file system aliases have some nice features which are not available to soft links, like labels, which cannot be used at all with soft links (well for a couple of seconds, it looks like you can, but they don't stick.) Another difference is that in 10.3, comments also don't stick, though they appear to do so in 10.4 (as a result of being Spotlight comments, probably). And of course, it is possible to create a file system alias using drag and drop. But one problem with using file system aliases instead of soft links is that you can't change your working directory (cd) to an alias of a directory.

So I created a command line executable to return the name of the Original file (in Finder parlence), including following soft links to aliases, and added a function to my .bashrc file to use that executable to get the name, and finally, to use that as the argument to the cd command. If there is no argument, the program calls the built-in cd routine, which changes to the user's home directory. If the argument tests as a directory (including soft link), the built-in cd is called with the given argument, because the system will use the name of the soft link in the path rather than the pointed-to directory. If the argument is a file or a soft link other than a directory, the true name is used as the argument to cd. Finally, if it is some other type of file, that argument is passed to the built-in cd, so the user gets the expected error message.

Here is the bash function I include in .bashrc. Note that the second elif requires double brackets for the test, because it include the logical operator or (||):

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"
    builtin cd "${1}"
And here's the C source code for getTrueName.

[robg adds: I tested this one, and it works perfectly (and very quickly in practice). You'll need to have the Developer Tools installed to compile the source, of course. Just copy and paste the source into a new file named getTrueName.c, then follow the build instructions included with the code. Once the executable is built, add the bash function to your .bashrc (or .bash_profile), and you're set -- you'll be able to cd into aliased directories from the command line. Very handy!]

Comments (10)

Mac OS X Hints