if判断的基本格式如下:
if 条件 then #then可省略 处理 end
1、判断文件是否存在
#!/usr/bin/env ruby
if File.exist?("/etc/hosts")
print "ok"
end加上else
#!/usr/bin/env ruby
if File.exist?("/etc/hosts")
print "ok"
else
print "error,file not exist"
end如果程序在后台运行,那么需要将打印改为写日志
#!/usr/bin/env ruby
require ‘logger‘
logger = Logger.new(‘/tmp/test.log‘,‘daily‘)
logger.sev_threshold = Logger::DEBUG
if File.exist?("/etc/hosts")
logger.debug "ok"
logger.close
else
logger.debug "error,file not exist"
logger.close
end2、判断文件是否可写
if File.writable?("/etc/hosts") { print "ok"}3、判断文件是否可读
if File.readable?("/etc/hosts")4、判断文件是否可执行
if File.executable?("/etc/hosts")5、判断文件大小
if File.size?("/etc/hosts") #文件大小非零为trueif File.zero?("/etc/hosts") #文件大小为零位true本文出自 “专注Linux 运维” 博客,转载请与作者联系!
原文地址:http://purplegrape.blog.51cto.com/1330104/1884353