How to get the fully resolved path of a symbolic link in Terminal

bashpythonsymlinkterminal

I have a tangled mess of python installations on my laptop. I was looking at the executables in /usr/local/bin and they are all symbolic links to ../../../Library......

There's some weird behavior surrounding this. If I do ls -lhaG I see ---> and the relative path to the right of the symlinks:

lrwxr-xr-x  1 root  wheel    69B Dec  7 22:29 python3 -> ../../../Library/Frameworks/Python.framework/Versions/3.1/bin/python3

However, I can't seem to get any of the command line tools to resolve that path and display the actual path to python3. I've found some tidbits here and there regarding use of pwd -P and the find utility to do this. The problem is that these don't seem to work on OS X the way that people describe them working on linux (i.e. outputting the full path to the symbolic link). They just print the symbolic links path for me:

FantasticMrFox:bin robert$ pwd -P python3
/usr/local/bin
FantasticMrFox:bin robert$ find `pwd -P` -name python3
/usr/local/bin/python3

Any ideas on what's going on here?

Best Answer

I think that pwd -P and readlink are going to be your friends for this task.

"How can I get the behavior of GNU's readlink -f on a Mac?" is a handy resource.

pwd -P only works if you're inside the symlink directory:

14:07:13 jason@mac ~ $ cd bin
14:08:08 jason@mac bin $ pwd -P
/Users/jason/Applications

readlink works by specifying the target (thus it can be used against files):

14:09:03 jason@mac ~ $ readlink bin
Applications

14:09:34 jason@mac ~ $ readlink /var
private/var

The output of readlink appears to be relative to the parent of the specified target.

Ex: The parent of /var is /, so private/var is correct, relative to /. Per my above example of bin -> Applications, both are in my Home Directory, no matter where I run it, the output is the same.