Reputation: 1389
I need to check if in a folder, at least one fine is linked (symbolik link) to a specific file. If yes, print string "OK", otherwhise "NO"
destination_folder="/home/my_folder"
symbolik_link="script.rb"
es) "ls -al" of the folder:
lrwxrwxrwx 1 test test 49 Nov 27 16:09 ruby_test1.rb -> ../test/calculator.rb
lrwxrwxrwx 1 test test 49 Nov 27 16:09 ruby_test2.rb -> ../test/sum.rb
lrwxrwxrwx 1 test test 49 Nov 27 16:09 ruby_test3.rb -> ../test/test.rb
Result: "NO"
es) "ls -al" of the folder:
lrwxrwxrwx 1 test test 49 Nov 27 16:09 ruby_test1.rb -> ../test/calculator.rb
lrwxrwxrwx 1 test test 49 Nov 27 16:09 ruby_test2.rb -> ../test/sum.rb
lrwxrwxrwx 1 test test 49 Nov 27 16:09 ruby_test3.rb -> ../test/script.rb
Result: "OK"
Upvotes: 1
Views: 31
Reputation: 4555
I missunderstood your question at first. Here's a new try.
To begin with, you can check if a file is a symlink with File.symlink?(file)
.
I'm going to assume that it's enough that the symlink points to the same path as the original file.
To "follow" a symlink, you can use Pathname#realpath
.
Like so:
require 'pathname'
wanted_file_path = File.expand_path('./lib/foo.rb')
directory = Dir.new('.')
found = directory.entries.any? do |entry|
if File.symlink?(entry)
Pathname.new(entry).realpath.to_s == wanted_file_path
end
end
if found
puts "Found a matching symlink"
else
puts "No matching symlink found"
end
Upvotes: 1