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.

admdrew
  • 3,790
  • 4
  • 27
  • 39
kch
  • 77,385
  • 46
  • 136
  • 148

3 Answers3

70

I think readlink is what you are looking for:

File.readlink("path/to/symlink")
Inshallah
  • 4,804
  • 28
  • 24
  • 16
    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 Sep 18 '09 at 15:43
  • @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 Sep 18 '09 at 16:25
48
require 'pathname'
Pathname.new("symlink").realpath

or readlink as others said

piotrsz
  • 1,132
  • 8
  • 12
16

Or you can try:

File.realpath("symlink_path")

Which works for both symlinks and normal files.

Juan Ibiapina
  • 300
  • 2
  • 7