在 RUBY 中,发现文件夹中是否至少有一个罚款被 linked - 具有符号 link - 到特定文件

In RUBY, discover if at least one fine in a folder is linked - has symbolik link - to a specific file

我需要检查在一个文件夹中,是否至少有一个罚款 linked (symbolik link) 到特定文件。如果是,打印字符串 "OK",否则 "NO"

destination_folder="/home/my_folder"
symbolik_link="script.rb"

es) "ls -al" 文件夹:

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

结果:"NO"

es) "ls -al" 文件夹:

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

结果:"OK"

起初我误解了你的问题。这是一个新的尝试。

首先,您可以检查文件是否是 File.symlink?(file) 的符号链接。

我假设符号链接指向与原始文件相同的路径就足够了。

要"follow"一个符号链接,可以使用Pathname#realpath

像这样:

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