File.open('~/newfile.txt', 'a+') do |f|
f << "hi..\n"
end
我有一个cron标签
* * * * * bash -lc 'ruby ~/scri.rb' >> /var/log/syslog
当我检查/ var / log / syslog中的日志时,我看到类似这样的条目
Sep 8 14:49:01 user1acer CRON[26063]: (user1) CMD (bash -lc 'ruby ~/scri.rb' >> /var/log/syslog)
Sep 8 14:50:01 user1acer CRON[27502]: (user1) CMD (bash -lc 'ruby ~/scri.rb' >> /var/log/syslog)
Sep 8 14:51:01 user1acer CRON[29006]: (user1) CMD (bash -lc 'ruby ~/scri.rb' >> /var/log/syslog)
Sep 8 14:52:01 user1acer CRON[30425]: (user1) CMD (bash -lc 'ruby ~/scri.rb' >> /var/log/syslog)
Sep 8 14:53:01 user1acer CRON[31846]: (user1) CMD (bash -lc 'ruby ~/scri.rb' >> /var/log/syslog)
但是,当我检查newfile.txt文件时,那里什么也看不到。
我在这里想念什么吗?
This has nothing to do with cron, actually. ~
is a feature of the shell, Ruby doesn't know what it is. Only some methods in Ruby deal with ~
, e.g. File::expand_path
. So, Ruby is literally trying to open a file named newfile.txt
in directory named ~
in the current working directory. Try it out yourself: create an empty directory named ~
in your home directory, and sure enough, after 1 minute, you should find a new file named newfile.txt
with the content hi..
in there.
There are a couple of ways to fix this, I will leave it up to you which one to use:
File.open(File.expand_path('~/newfile.txt'), 'a') do |f| end
File.open(File.join(Dir.home, 'newfile.txt'), 'a') do |f| end
[Note: if you only want to append to the end of the file, not move around or read, a
is enough, you don't need a+
.]
请参阅有关文档File::expand_path
((大胆的强调我的):
expand_path(file_name [, dir_string] )
→abs_file_name
将路径名转换为绝对路径名。除非
dir_string
给出了相对路径,否则将从过程的当前工作目录中引用相对路径,在这种情况下,它将用作起点。给定的路径名可以以“ 〜 ”开头,该名称会扩展到流程所有者的主目录(HOME
必须正确设置环境变量)。“ 〜user ”扩展到指定用户的主目录。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句