RamanSM
RamanSM

Reputation: 283

ruby script cron not working

enter image description hereI have a ruby script in ~/scri.rb

File.open('~/newfile.txt', 'a+') do |f|
  f << "hi..\n"
end

I have a cron tab like this

* * * * * bash -lc 'ruby ~/scri.rb' >> /var/log/syslog

When I check the logs in /var/log/syslog I see entries like this

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)

But when I check the newfile.txt file I see nothing in there.

Am I missing something here ?

Upvotes: 1

Views: 182

Answers (1)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369458

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+.]

See the documentation for File::expand_path (bold emphasis mine):

expand_path(file_name [, dir_string] )abs_file_name

Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point. The given pathname may start with a “~”, which expands to the process owner’s home directory (the environment variable HOME must be set correctly). “~user” expands to the named user’s home directory.

Upvotes: 2

Related Questions