Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In shell script, how can I dereference a symbolic link and get the directory of the file it links to?

share|improve this question
up vote 2 down vote accepted

You can dereference symbolic links with GNU readlink through:

readlink -f /path/to/symlink

The directory is easy to get through dirname:

dirname $(greadlink -f /path/to/symlink)

Note that BSD readlink (i.e. the one that comes with OS X) does not support this -f option, but installing coreutils through Homebrew will provide you with greadlink.

A cross-platform solution with Python:

python -c 'import os;print os.path.dirname(os.path.realpath("***/path/to/symlink***"))'
share|improve this answer
Thank you. It worked. :) – gabriel Jul 21 '12 at 0:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .