4

In OS X, how can I dereference a symbolic link to a canonical file name? (i.e. one starting with /.)

That is, I'm after the equivalent of GNU readlink's -f option:

kapow:~$ greadlink -f .bash_profile
/Users/mjs/.config/home/.bash_profile

OS X's readlink instead returns a relative link:

kapow:~$ readlink .bash_profile
.config/home/.bash_profile

stat(1) does have an amazing number of options, but I couldn't figure out the right combination to do what I want.

ithinkihaveacat
  • 1,604
  • 3
  • 14
  • 18

1 Answers1

3

The most straightforward solution is to test the return value and prepend pwd if you find that the readlink has returned a relative path rather than an absolute path stored in the link. Anything not starting with / is simple to test with a variety of unix tools.


I don't know if this was a conscious design decision since OS X prefers file system aliases which track a file's unique id as well as the path or is just an omission / difference carried forth from BSD. What is clear is that there is no option to synthesize the full path of the linked file using the OS X version of readlink.

Here are several ready made solutions to implement read link -f on OS X from another site...

If you are a fan of GNU tools, you'll want to get homebrew and install the coreutils package - you can then alias greadlink for readlink and carry on with a minimal amount of fuss.

Glorfindel
  • 1,213
  • 3
  • 15
  • 22
bmike
  • 283
  • 1
  • 19