Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the target of a symlink?

Tags:

ruby

symlink

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.

like image 420
kch Avatar asked Aug 06 '09 09:08

kch


People also ask

How do you find the target of a symbolic link?

The Symlink option (Symlink Target Operations) only appears in the context menu from ClearCase Explorer after right-clicking on an actual symbolic link. If the symlink target is in another VOB, then that VOB must also be mounted on the local system.

How do I find the target of a symbolic link in Windows?

When you right-click a file to open up "Properties" window, it includes an additional tab: "Link Properties", showing the Target of symlinks. You can also edit this Target field to change the symlink's target. And since the field is editable, copy-paste of the target link is easy.

How do I find the path of a soft link?

Showing soft link using Find command in Unix When you use the find command with option type and specify the type as small L ( l for the link), it displays all soft links in the specified path.

How do I get a list of symbolic links?

Use the ls -l command to check whether a given file is a symbolic link, and to find the file or directory that symbolic link point to. The first character “l”, indicates that the file is a symlink. The “->” symbol shows the file the symlink points to.


2 Answers

I think readlink is what you are looking for:

File.readlink("path/to/symlink") 
like image 185
Inshallah Avatar answered Sep 27 '22 23:09

Inshallah


require 'pathname' Pathname.new("symlink").realpath 

or readlink as others said

like image 22
piotrsz Avatar answered Sep 27 '22 23:09

piotrsz