1

In ruby, how can I read all symlinks at a path and put them in an array- eg, I have below symlinks at a path /bin-

current_instance1 -> ABC
current_instance2 -> DEF
current_instance3 -> GHI

I want to read all the symlinks starting with "current_" and populate them into an array

user6378152
  • 257
  • 2
  • 6
  • 11

2 Answers2

0

If you only want to list all symlinks:

Dir.glob("/path/to/dir/*").find_all { |file| File.symlink?(file) }

If you want to list symlinks with their targets:

Dir.glob("/path/to/dir/*").map { |file|  {file => File.readlink(file)} if File.symlink?(file) }.compact
shivam
  • 16,048
  • 3
  • 56
  • 71
0
Dir.glob("/<path_to_dir>/current_*").map{ |file| File.readlink(file) if File.symlink?(file) }.compact

Explanation:

Dir.glob("/<path_to_dir>/current_*") # Matches all files beginning with current_ in the specified path

Dir.glob("/<path_to_dir>/*current_") # Matches all files ending with current_ in the specified path

Dir.glob("/<path_to_dir>/*current_*") # Match all files that have c in them (including at the beginning or end) in the specified path

.map { |file| # iterates and pushes result into array

File.readlink(file) if File.symlink?(file) # Get the target file if the file is a symlink

}.compact # if the file is not a symlink in the specified path, map fills nil by default. Using compact at the end removes all nil entries from the resulting array and gives you only symlink target files in an array.

UPDATE: OP wanted only the filename for that we should be using File.basename(File.readlink(file))

Vamsi Krishna
  • 3,742
  • 4
  • 20
  • 45
  • thanks Vamsi, but it returns the whole path along with the directory name- ["/ABC" , "/DEF", "/GHI"] while I want only ["ABC", "DEF", "GHI"]. how can I do that? – user6378152 Jun 22 '17 at 14:31