How do I get the target of a symlink?
Asked Answered
C

3

53

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.

Cicala answered 6/8, 2009 at 9:45 Comment(1)
Incidentally, in bash it's also just readlink path/to/symlink. Never parse the output of ls.Gesticulative
E
70

I think readlink is what you are looking for:

File.readlink("path/to/symlink")
Explore answered 6/8, 2009 at 9:55 Comment(3)
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.Goraud
@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.Explore
To say it differently: This call will resolve symlink, but it will resolve neither path or to.Lindell
W
50
require 'pathname'
Pathname.new("symlink").realpath

or readlink as others said

Wesleyanism answered 6/8, 2009 at 9:56 Comment(1)
rather Pathname.new("/path/to/symlink").realpath.to_s :) .. this is definitely better than using system()Alamein
R
16

Or you can try:

File.realpath("symlink_path")

Which works for both symlinks and normal files.

Redwine answered 14/8, 2014 at 14:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.