如何检查Ruby中一个命令是否存在一个目录/文件/符号链接?

时间:2020-12-05 00:03:28

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").

我需要一个函数,因为我需要检查可能是目录、文件或符号链接的路径数组。我知道File.exists吗?“file_path”适用于目录和文件,但不适用于符号链接(即文件.symlink?“symlink_path”)。

2 个解决方案

#1


104  

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"

OP:“谢谢,但我需要三个真假”

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

#2


11  

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

为什么不定义你自己的函数文件。存在?(路径)或文件。符号链接?(路径)并使用它?

#1


104  

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"

OP:“谢谢,但我需要三个真假”

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

#2


11  

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

为什么不定义你自己的函数文件。存在?(路径)或文件。符号链接?(路径)并使用它?