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
end
2、判断文件是否可写
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") #文件大小非零为true
if File.zero?("/etc/hosts") #文件大小为零位true
6、如果仅仅是判断是否为真,也可以简写,比如
a = 5
if a > 4
b = 3
end
puts a
puts b
c = 1
d = 3 if (c < 6)
puts c
puts d
puts "ok" if a > b