2

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

2

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***"))'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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