11

I have to run a command in the background but I want to have proper escaping for its parameter.

system("rake send_mails subject='#{params[:subject]}' 2> /dev/null 1> /dev/null &");

If I write system("rake", "send_mails", params[:subject]) then I don't have "place" for redirections and the & sign. If I don't I do not have escaping for the subject parameter.

How can I resolve this?

Notinlist
  • 16,144
  • 10
  • 57
  • 99
  • I am not sure, but did you try to nest `system` calls? For example: `system(system("rake", "send_mails", params[:subject]), "/dev/null 1> /dev/null &")` – fl00r May 10 '11 at 11:11
  • The inner `system()` call is executed then the outer `system()` fails without executing anything: `TypeError: can't convert true into String` – Notinlist May 10 '11 at 11:24

1 Answers1

20

In Ruby 1.9, try Process.spawn:

# Spawn a new process and run the rake command
pid = Process.spawn({"subject" => params[:subject]},
                    "rake", "send_mails",
                    :out => 'dev/null', :err => 'dev/null')

# Detach the spawned process
Process.detach pid
Lars Haugseth
  • 14,721
  • 2
  • 45
  • 49
  • The point would be not to wait at all. We have to move on to processing the next web query - as I failed to mention it. But that's the point in redirecting the output to `/dev/null` and running with `&` - to reach complete detachment. – Notinlist May 10 '11 at 11:50
  • 1
    Then use Process.detach after you've spawned the new process. I will edit my answer to include this. – Lars Haugseth May 10 '11 at 12:03
  • 1
    Adding that `Process.fork do ... end` is available and close-to-perfect in 1.8.7. – Notinlist May 10 '11 at 12:08
  • 1
    But I am still hungry for a function like PHP's `escapeshellarg()`. – Notinlist May 10 '11 at 12:58
  • I know it has been a while, but there is Shellwords: http://stackoverflow.com/questions/5949008/executing-shell-command-in-background-from-ruby-with-proper-argument-escaping – radiospiel Jun 23 '15 at 11:56
  • @radiospiel Your link points to this very page. Maybe some copy-paste mistake? – Notinlist Jan 29 '16 at 08:40
  • @Notinlist my bad, the correct link would probably be something line http://ruby-doc.org/stdlib-2.0.0/libdoc/shellwords/rdoc/Shellwords.html – radiospiel Jan 30 '16 at 13:26