如何使用 Ruby 中的一个命令检查目录/文件/符号链接是否存在 [英] How to check if a directory/file/symlink exists with one command in Ruby
问题描述
有没有一种方法可以检测目录/文件/符号链接/等.实体(更广义)存在吗?
Is there a single way of detecting if a directory/file/symlink/etc. entity (more generalized) exists?
我需要一个函数,因为我需要检查一个路径数组,这些路径可以是目录、文件或符号链接.我知道 File.exists?"file_path"
适用于目录和文件,但不适用于符号链接(即 File.symlink?"symlink_path"
).
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"
).
推荐答案
标准文件模块具有通常的 文件测试可用:
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:谢谢,但我需要所有三个真或假"
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
这篇关于如何使用 Ruby 中的一个命令检查目录/文件/符号链接是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!