views:

804

answers:

2

I have a string containing the file system path to an existing symlink. I want to get the path that this link points to.

Basically I want the same that I'd get through this bit of hackery:

s = "path/to/existing/symlink"
`ls -ld #{s}`.scan(/-> (.+)/).flatten.last

but I want to do it without shelling out.

+9  A: 

I think readlink is what you are looking for:

File.readlink("path/to/symlink")
Inshallah
Note that if the symlink is relative or there is a chain of symlinks, this will not follow all the links or return the full path -Pathname#realpath will.
mfazekas
@mfazekas, thank you for pointing this out; I wonder whether that's really what the OP wanted though; `ls -ld ...` doesn't give the real path either.
Inshallah
+10  A: 
require 'pathname'
Pathname.new("symlink").realpath

or readlink as others said

piotrsz
rather Pathname.new("/path/to/symlink").realpath.to_s :) .. this is definitely better than using system()
Rishav Rastogi