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

发布于 2024-10-16 00:50:32 字数 197 浏览 7 评论 0原文

是否有一种方法可以检测目录/文件/符号链接/等是否存在。实体(更广义)存在吗?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

万劫不复 2024-10-23 00:50:32

标准文件模块具有常用的文件测试

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

您应该能够在那里找到你想要的东西。


OP:“谢谢,但我需要所有三个正确或错误的”

显然不是。好的,尝试一下:

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

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
怀中猫帐中妖 2024-10-23 00:50:32

为什么不定义自己的函数 File.exists?(path) 或 File.symlink?(path) 并使用它呢?

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

浮萍、无处依 2024-10-23 00:50:32

只需 File.exist? 本身即可为您处理上述所有问题

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文