Say for example I have these types of paths to files in a script:


Is there a command I can call such as readlink that will convert this path to its actual physical form:

  • 2
    Note that it may not be /path/to/file1.txt if /path/to/some/file or /path/to/some is a symlink. – Stéphane Chazelas Sep 17 '13 at 20:27
  • If file1.txt is a symlink, do you want to follow it? What do you want to happen if the file doesn't exist or is a broken symlink? – Gilles 'SO- stop being evil' Sep 17 '13 at 22:49
  • Thanks for the clarification, I meant the above was only real files and no symlinks, but I should've said as much. – slm Sep 17 '13 at 23:31

Ah, asked too quickly. On Linux, the answer is to use readlink with the -m switch:

$ readlink -m /home/saml/web/../web_login_form_examples/basic-php-parsing.zip

readlink man page

-m, --canonicalize-missing
       canonicalize by following every symlink in every component of the
       given name recursively, without requirements on components existence

If you aren't interested in following file.txt when it's a symbolic link, and you're assuming that the file exists:

canonical_directory=$(cd -- "$(dirname -- "$filename")/" && pwd -P)
echo "$canonical_directory/${filename##*/}"

This is fully portable (except to some pre-POSIX antiques).

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.