Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

/path/to/some/file/../../file1.txt

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

/path/to/file1.txt
share|improve this question
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 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

2 Answers 2

up vote 4 down vote accepted

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
/home/saml/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
share|improve this answer

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

filename=/path/to/file1.txt
canonical_directory=$(cd -- "$(dirname -- "$filename")/" && pwd -P)
echo "$canonical_directory/${filename##*/}"

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

share|improve this answer

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.