Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a variable to a system() call in ruby?

Let's say I have a bunch of text in a variable, some_var, that could be pretty much anything.

some_var = "Hello, I'm a \"fancy\" variable | with a pipe, double- and single-quotes (terminated and unterminated), and more."

Let's also say that, in a CLI Ruby application, I want to allow the user to pipe that text into any Unix command. I've allowed them to input something like some_var | espeak -a 200 -v en-us, where the command to the right of the pipe is any unix CLI tool installed on their system.

Let's also say that I already took care of separating the variable choice and the pipe out of their input, so I know for 100% certainty exactly what command is after the pipe. (In this case, I want to pipe the contents of the variable to espeak -a 200 -v en-us.)

How would I do this? I don't think I can use the backtick method, or the %x[] literal. I've tried doing the following...

system("echo '#{some_var}' | espeak -a 200 -v en-us")

...but any special characters screw things up, and I can't remove the special characters. What should I do?

like image 809
Kerrick Avatar asked May 24 '12 06:05

Kerrick


1 Answers

Besides popen you could also look at Shellwords.escape:

puts Shellwords.escape("I'm quoting many different \"''' quotes")
=> I\'m\ quoting\ many\ different\ \"\'\'\'\ quotes

This will take care of quoting special characters for you (bash compatible):

system("echo '#{Shellwords.escape(some_var)}' | ....")

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/shellwords/rdoc/Shellwords.html

like image 167
Casper Avatar answered Sep 27 '22 22:09

Casper