How to check if a directory/file/symlink exists with one command in Ruby

RubyFileDirectorySymlinkExists

Ruby Problem Overview


Is there a single way of detecting if a directory/file/symlink/etc. entity (more generalized) exists?

I need a single function because I need to check an array of paths that could be directories, files or symlinks. I know File.exists?"file_path" works for directories and files but not for symlinks (which is File.symlink?"symlink_path").

Ruby Solutions


Solution 1 - Ruby

The standard File module has the usual file tests available:

RUBY_VERSION # => "1.9.2"
bashrc = ENV['HOME'] + '/.bashrc'
File.exist?(bashrc) # => true
File.file?(bashrc)  # => true
File.directory?(bashrc) # => false

You should be able to find what you want there.


>OP: "Thanks but I need all three true or false"

Obviously not. Ok, try something like:

def file_dir_or_symlink_exists?(path_to_file)
  File.exist?(path_to_file) || File.symlink?(path_to_file)
end

file_dir_or_symlink_exists?(bashrc)                            # => true
file_dir_or_symlink_exists?('/Users')                          # => true
file_dir_or_symlink_exists?('/usr/bin/ruby')                   # => true
file_dir_or_symlink_exists?('some/bogus/path/to/a/black/hole') # => false

Solution 2 - Ruby

Why not define your own function File.exists?(path) or File.symlink?(path) and use that?

Solution 3 - Ruby

Just File.exist? on it's own will take care of all of the above for you

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionclaudiutView Question on Stackoverflow
Solution 1 - Rubythe Tin ManView Answer on Stackoverflow
Solution 2 - RubyGintautas MiliauskasView Answer on Stackoverflow
Solution 3 - RubygrepsedawkView Answer on Stackoverflow