Directory of dereferenced symbolic link?

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


Solution 1:

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