Question

What is the equivalent Perl command to the GNU coreutils command readlink -f?

If any component of the file name except the last one is missing or unavailable, readlink produces no output and exits with a nonzero exit code. A trailing slash is ignored.

Was it helpful?

Solution

You can use Cwd:

use Cwd 'abs_path';
my $path = "/some/arbitrary/path";
print abs_path($path);

Test:

for q in exists imaginary imarginary/imaginary ; do
   echo "$q"
   echo -n "readlink -f: " ; readlink -f "$q"
   echo -n "abs_path:    " ; perl -MCwd=abs_path -E'say abs_path $ARGV[0]' "$q"
   echo
done

Output:

exists
readlink -f: /home/eric/exists
abs_path:    /home/eric/exists

imaginary
readlink -f: /home/eric/imaginary
abs_path:    /home/eric/imaginary

imaginary/imaginary
readlink -f: abs_path:

OTHER TIPS

As a total Perl rookie, I'm happy to say I have figured out this STDIN solution all by myself (after several tries, remember that Perl's learning curve IS known to be steep). devnull's solution was great with no doubt, but it was a little too "scriptish" for my taste - whereas I'd sometimes just want to pipe a perl one-liner to an echo'ed string, like this:

echo "/home/user/somesymlinkedpath" | perl -MCwd=abs_path -nle 'print abs_path $_'

So as there might be more people around who want to know about how to code this kind of piped form (making perl read the argument from STDIN), I've decided to post it here too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top