How to execute commands within Rake tasks?

palani picture palani · Sep 8, 2010 · Viewed 28.4k times · Source

I have the rake tasks in my rails application. i want to run a commandline commands with in rake task. how can i do this. i tried by the following but fails

desc "Sending the newsletter to all the users"
task :sending_mail do
  run "cd #{RAILS_ROOT} && ar_sendmail -o -t NewsLetters -v"
  system "cd #{RAILS_ROOT} && ar_sendmail -o -t NewsLetters -v &"
end

The above run command throws run method undefined & System command not throwing any errors but not executed.

Answer

Rake sh built-in task

This is probably the best method:

task(:sh) do
  sh('echo', 'a')
  sh('false')
  sh('echo', 'b')
end

The interface is similar to Kernel.system but:

  • it aborts if the return is != 0, so the above never reaches echo b
  • the command itself is echoed before the output