Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

share|improve this question
add comment

1 Answer 1

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.