Forum: Ruby Testing Symlinks

Posted by Thomas Sawyer (7rans)
on 2010-03-09 19:09
(Received via mailing list)
I probably should know the answers to these, but it's never come up
before.

How to check if a symbolic link exists and already points to where you
expect it to point?

And how to check for dead symbolic links?

Thanks.
Posted by Gary Wright (Guest)
on 2010-03-09 19:29
(Received via mailing list)
On Mar 9, 2010, at 1:08 PM, Intransition wrote:

> I probably should know the answers to these, but it's never come up
> before.
> 
> How to check if a symbolic link exists and already points to where you
> expect it to point?
> 
> And how to check for dead symbolic links?

Try playing around with the following:

def info(path)
  lstat = File::lstat(path) rescue nil
  return "not found" unless lstat
  if lstat.symlink?
    target = File::readlink(path)
    stat = File::stat(path) rescue nil
    if stat
      "symlink to #{target}"
    else
      "dead symlink to #{target}"
    end
  else
    "not a symlink"
  end
end

ARGV.each { |f|
  puts "#{f}: #{info(f)}"
}
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.